Reputation: 851
I'm working in a suite testing for one of my modules in my App.
I'm importing a module in my test file that has an execution of an asynchronous function that sets a variable in the module necessary for the test to work.
Below is the code:
// imported module
let bar;
//async function definition
const async_function = async () => {
// code that change the value of bar
};
// call to the async function
async_function();
module.exports.foo = async () => {
// code that needs the value of bar which is set in async_function
};
// test file
const { foo } = require('./imported_module');
describe('test', () => {
it('should wait the promise in the imported module', async () => {
// here the call to foo is crashing because the value of bar is not assigned yet
const res = await foo();
expect(res).toBe(something);
});
});
This code works well in production because the assignation to bar is being done when the server starts so when the requests starts to arrive, the value is already assigned.
Any help with this issue please?
Thanks!
Upvotes: 2
Views: 1591
Reputation: 665286
Do not use mutable variables that are initialised asynchronously. Use a promise:
// imported module:
async function init() {
// code that **returns** the value of bar
}
// call to the async function, storing the result in a promise
const barPromise = init();
// handle errors in the initialisation
barPromise.catch(err => { console.error(err); process.exit(1); }); // or ignore them?
module.exports.foo = async () => {
const bar = await barPromise;
// code that needs the value of bar
};
Upvotes: 3
Reputation: 416
Just export result of async function call from your module:
module.exports.ready = async_function();
Import and await for it in the test. Also, it is a good idea to wait for it in production as well, it is not good practice just to assume that no request arrives before async initializations had time to complete.
Upvotes: 3