我正在为我的应用程序中的一个模块测试套件。
我正在我的测试文件中导入一个模块,该模块执行一个异步函数,该函数在测试工作所需的模块中设置一个变量。
代码如下:
// 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);
});
});
此代码在生产环境中运行良好,因为对 bar 的赋值是在服务器启动时完成的,因此当请求开始到达时,该值已经被赋值。
请帮忙解决这个问题?
谢谢!
最佳答案
只需从您的模块导出异步函数调用的结果:
module.exports.ready = async_function();
在测试中导入并等待它。此外,在生产环境中等待它也是一个好主意,仅仅假设在异步初始化有时间完成之前没有请求到达并不是好的做法。
关于javascript - 等待 Promise 在测试中导入的模块中解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67274844/