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.
CodePudding user response:
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 () => {