Intellisense show wrong properties for a Promise inside `async` method - javascript

I've noticed that, when a Promise is used inside an async method, a lot of properties which should be in the IntelliSense are actually there.
Take this simple code for example (i'm using REACT and I'm inside a Hook component, just for give you a context).
const notAsyncMethod = () => {
let a : Promise<string> = new Promise(null);
}
const asyncMethod = async () => {
let a : Promise<string> = new Promise(null);
}
Now, in the first case, this is the IntelliSense suggestions:
Which is exactly what I expect.
Then, in the second case, this is what IntelliSense suggests me:
Why is this happening? Is it normal, or there might be some problem with my code? And, if this is how it should work.. Why is this happening, and from what those properties are coming?

Related

Function's parameter used inside a previously defined variable (String) returns undefined

trying to declare a variable for an API call (There are different website versions for API calls so want to have it dynamically interchangeable while having clean code).
It goes like this:
const getAbi = async (addy) => {
const url = `https://api.arbiscan.io/api?module=contract&action=getabi&address=${addy}&apikey=${arbiscanKey}`;
const abi = await axios.get(url);
console.log(abi);
return abi;
};
Now, its supposed to take the function parameter (Named "addy") and input it inside the API call link. For some reason, it does not do that. It gives me error:
const arbiscanGetAbi = `https://api.arbiscan.io/api?module=contract&action=getabi&address=${addy}&apikey=${arbiscanKey}`;
^
ReferenceError: addy is not defined
Not sure how to get it to realise i am referring to "addy" from the function parameter, thanks!

how to test class methods with jest (on return values)

Im trying to write unit tests for class methods with jest ( new to jest)
I have methods that e.g. take arrays and modify them and bring them into different form to satisfy algorithm needs.
But I dont see a way how I simply can test class method receiving and returning values.
Looks like there is a problem with classes, class methods cant be tested as simple functions.
But if I look at the docs I dont see it covering these topics, it only covers e.g. was a class instance called, was a class method called..
Edited:
this is my code example
import MyClass from "../MyClass.js";
// mocked data
const inputArrayMock=[{someObject}]
const outputArrayMock=[{modifiedObject}]
test("test MyClass method a", () => {
const obj = new MyClass();
const result = obj.methodA(inputArrayMock);
expect(result).toEqual(outputArrayMock);
});
I just ran my code again, it's throwing the error:
Received: {Symbol(async_id_symbol): 293, Symbol(trigger_async_id_symbol): 281, Symbol(destroyed): {"destroyed": false}}
Note: Both arrays (in- and output values I wrote as mock data. The expected array is correct, but the received not, which throws the error.
Without knowing your code I can only make a guess.
import MyClass from "../MyClass.js";
test("your test name", () => {
const obj = new MyClass();
const result = obj.theMethodYouWantToCheck();
expect(result).toBe("the desired result");
});
I had a similar issue and it turned out to be async/await related. Again without knowing the class or method your calling, this is just an educated guess.
Try adding async to the test method and call the method with await.
import MyClass from "../MyClass.js";
test("your test name", async () => {
const obj = new MyClass();
const result = await obj.theMethodYouWantToCheck();
expect(result).toBe("the desired result");
});
This fixed the issue for me. Don't know if its still an issue you're facing, as it's an 8 month old ticket but just for any future googlers.

How to get/set out-of-scope variables when testing a function with dependency on these (jest)?

I'm trying to have full test coverage on some helper functions in my project. My first tests for either of the functions checks whether 2 out-of-scope variables are declared or not, which run successfully.
What I want to do is, jest to set/mock wrapper and layer variables declared out-of-scope of the functions to be tested, but can't seem to have it right no matter how hard I tried.
Thankful and appreciate any kind of help in this direction as I'm fairly rookie in terms of writing tests in general not to mention tests for jest.
I have tried jest.mock by mocking by default my imported module and then did jest.requireActual on 2 functions.
I have tried jest.doMock with a module factory which sets these 2 variables and then returns in an object.
Module: helpers/index.js
let wrapper; // Is created on runtime ergo initially undefined.
const layer = document.createElement('div');
layer.classList.add('layer');
const isElement = elm => {
if (!(elm instanceof Element)) {
throw new Error('Given element is not of type Element or is undefined!');
}
}
export const someFn = async () => {
wrapper = document.querySelector('.wrapper');
isElement(wrapper);
isElement(layer);
// Code that needs to be tested
// but cannot since when testing this function
// 'wrapper' and 'layer' are always undefined.
}
Test: helpers/index.test.js
// Helpers
import {someFn} from 'helpers';
describe('Method: someFn', () => {
test('should NOT throw', async () => {
await expect(someFn()).resolves.not.toThrow(); // but it does!
});
});
Actual result: Received promise rejected instead of resolved
Expected result: Not to throw, considering these out-of-scope variables that this function relies on, can somehow be set/mocked while testing it.

How to get a constructor function from the window object in TestCafe?

In my testcafe tests, I need to get the constructor function for a library I am using in order to call a static method on it.
However, I am unable to do this using the given ClientFunction and Eval methods. How can I go about getting the constructor function?
I have tried the following:
// Does not work, because the docs say it only allows using ClientFunction for obtaining "serializable" values
let getSortable = new ClientFunction(() => window.Sortable);
test('test', async t => {
let Sortable = await getSortable();
console.log(Sortable); // Logs undefined
});
test('test', async t => {
let Sortable = await t.eval(() => window.Sortable);
console.log(Sortable); // Logs undefined (not sure why)
});
I need to get the constructor function for a library I am using in order to call a static method on it.
It's impossible to do that. You cannot call function from the browser's JavaScript environment in the Node.js environment in which tests are executed.
To accomplish your scenario, call the target static method in the ClientFunction and return the result from it.
cosnt getStaticData = ClientFunction(() => {
const data = window.Sortable.staticMethod();
return JSON.serializable(data);
});

Getting around an async/await issue

I am creating a simple node script to learn the functionality of Cosmos DB. I want to create a way to not have to provide the following at the top of every async function (yes, I know I could chain the async calls with but that means still means I have to use a new db instance at the top of every function. So, I want to do something like this:
const {database} = await client.databases.createIfNotExists({id: databaseId});
const {container} = await database.containers.createIfNotExists({id: containerId});
With that said, I've bumped my head on this for a few hours and can't find a way to create one database and one container for all my functions to share. The idea (but not implementation because it doesn't work, is to do something like this:
getConnections = async () => {
const {database} = await client.databases.createIfNotExists({id: databaseId});
const {container} = await database.containers.createIfNotExists({id: containerId});
let connections = {};
connections.db = database;
connections.container = container;
return connections;
};
But since the getCoonections method is async (which it must be because the methods that would use it are, too) the function doesn't necessarily finish before the first insert is made in another function, thereby causing an exception.
Has anyone found a way to centralize these objects so I don't have to declare them in each async function of my app?
It sounds like you need to get these connections before the app does anything else. So why not simply make the loading of your app use async/await too?
async function init() {
const connections = await getConnections();
const app = initializeTheRestOfYourApp(connections); // now safe to do inserts
};
init();
This pretty much works now, Not sure why as there is no blocking between this init() and the next async method in the call chain uses the connection, but it's working. – David Starr - Elegant Code just now

Categories

Resources