Jest – 尝试在Node Jstesting中模拟asynchronous等待

我正在尝试使用Jest进行我的Node Jstesting(特别是AWS的Lambda),但是我很难模拟asynchronous等待function。

我正在使用babel-jest和jest-cli。 以下是我的模块。 我得到第一个console.log,但第二个console.log返回未定义和我的testing崩溃。

任何想法如何实现这个?

以下是我的模块:

import {callAnotherFunction} from '../../../utils'; export const handler = async (event, context, callback) => { const {emailAddress, emailType} = event.body; console.log("**** GETTING HERE = 1") const sub = await callAnotherFunction(emailAddress, emailType); console.log("**** Not GETTING HERE = 2", sub) // **returns undefined** // do something else here callback(null, {success: true, returnValue: sub}) } 

我的testing

 import testData from '../data.js'; import { handler } from '../src/index.js'; jest.mock('../../../utils'); beforeAll(() => { const callAnotherLambdaFunction= jest.fn().mockReturnValue(Promise.resolve({success: true})); }); describe('>>> SEND EMAIL LAMBDA', () => { test('returns a good value', done => { function callback(dataTest123) { expect(dataTest123).toBe({success: true, returnValue: sub); done(); } handler(testData, null, callback); },10000); }) 

jest.mock('../../../utils'); 是好的,但是你实际上并没有嘲笑实现,你必须自己实现这个行为。

所以你需要添加

 import { callAnotherFunction } from '../../../utils'; callAnotherFunction.mockImplementation(() => Promise.resolve('someValue')); test('test' , done => { const testData = { body: { emailAddress: 'email', emailType: 'type } }; function callback(dataTest123) { expect(dataTest123).toBe({success: true, returnValue: 'someValue'); done(); } handler(testData, null, callback); }); 

希望这可以帮助。