首页 > 解决方案 > 等待 Promise 在测试中导入的模块中解析

问题描述

我正在为我的应用程序中的一个模块进行套件测试。

我在我的测试文件中导入了一个模块,该模块执行了一个异步函数,该函数在模块中设置了一个测试工作所需的变量。

下面是代码:

// 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的分配正在完成,因此当请求开始到达时,该值已经分配。

请问这个问题有什么帮助吗?

谢谢!

标签: javascriptnode.jsjestjs

解决方案


只需从模块中导出异步函数调用的结果:

module.exports.ready = async_function();

导入并在测试中等待它。此外,在生产中等待它也是一个好主意,仅仅假设在异步初始化有时间完成之前没有请求到达并不是一个好习惯。


推荐阅读