javascript - 等待 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的分配正在完成,因此当请求开始到达时,该值已经分配。
请问这个问题有什么帮助吗?
谢谢!
解决方案
只需从模块中导出异步函数调用的结果:
module.exports.ready = async_function();
导入并在测试中等待它。此外,在生产中等待它也是一个好主意,仅仅假设在异步初始化有时间完成之前没有请求到达并不是一个好习惯。
推荐阅读
- amazon-web-services - 使用标签键限制对 DynamoDB 的访问
- django - Django模板继承没有完全工作
- django - 如何解决 NoReverseMatch
- sql - 从函数中删除无用的时区
- php - 如何将内容批量插入数据库中的每个帖子?
- javascript - 使用此关键字的打字稿
- oracle - 在 oracle 中,创建 table newtable nologging parallel 4 as select * from existing table ;锁定现有表?
- android - 使用switchMap android发送网络请求
- node.js - 推送到 git 远程仓库后 node_modules 文件夹丢失
- c - 格式化字符串前的`_`有什么用?