javascript - 等待 Promise 在测试中导入的模块中解析

标签 javascript node.js jestjs

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

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

代码如下:

// 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/

相关文章:

javascript - 如何从vue路由器中仅提取路由来生成站点地图

javascript - 如何从 Javascript 将字符串写入标准输出

node.js - TypeError : obj. hasOwnProperty 在调用 Graphql mutation 时不是一个函数

javascript - vue组件在加载页面时不显示。如何让它显示?

javascript - 如何从php获取数据到jquery

javascript - 如何在范围变量angularjs中保存文本框值

javascript - ReactJS 和 jest : how to use a mock value for element. offsetWidth?

javascript - Angular 动画查询错误地返回零元素

javascript - 如何将 Jest 中的 '__mocks__' 文件夹移动到/test?

api - 如何使用 JEST 模拟通知 API?