简体   繁体   中英

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

I have written an asynchronous function in a file called index.js as follows:

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

However, when I try to write a test file called index.test.js, with the following code:

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);
});

, I get an error saying that exportedModule.func is not asynchronous, even through it clearly is. I cannot use promises ( .then and .catch ) to run the tests, as the test file will be deemed finished before the code in the .then / .catch is executed. Is there a way I'm supposed to be properly importing func such that I can use await ? Ideally I would like this to be done within the test file itself without changing index.js.

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

I think you're misreading the error. It's saying that the function in your test is not async . You can only use await in an async function. To fix it, add async to the function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM