如何在 javascript 中正确导入异步 module.exports 函数

how to correctly import an asynchronous module.exports function in javascript

我在名为index.js的文件中写了一个异步函数如下:

module.exports.func = async (obj) => {
    return {
      statusCode: 200,
      body: JSON.stringify({
        message: 'Success!',
        input: obj,
      }),
    };
};

但是,当我尝试使用以下代码编写名为 index.test.js 的测试文件时:

const exportedModule = require('./index');

test('Successfully execute func when empty object passed', () => {
  const obj = {};
  const expectedReturn = {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Success!',
      input: obj,
    }),
  };
  const actualReturn = await exportedModule.func(obj);
  console.log(actualReturn);
  expect(actualReturn).toBe(expectedReturn);
});

,我收到一条错误消息说 exportedModule.func 不是异步的,即使通过它显然是。我不能对 运行 测试使用承诺(.then.catch),因为测试文件将在 .then/.catch 中的代码之前被视为完成被执行。有什么方法可以正确导入 func 以便我可以使用 await?理想情况下,我希望在不更改 index.js.

的情况下在测试文件本身内完成此操作

I get an error saying that exportedModule.func is not asynchronous

我认为您误读了错误。意思是你的 test 中的函数不是 async。您只能在 async 函数中使用 await。要修复它,请将 async 添加到函数中。

//                                                 added:  VVVVV
test('Successfully execute func when empty object passed', async () => {