JestJS - 尝试在 Node JS 测试中模拟 Async Await

2023-12-27

我正在尝试使用 Jest 进行 Node Js 测试(特别是 AWS 的 Lambda),但我在模拟异步等待功能时遇到困难。

我正在使用 babel-jest 和 jest-cli。以下是我的模块。我正在访问第一个 console.log,但第二个 console.log 返回未定义并且我的测试崩溃。

关于如何实现这一点有什么想法吗?

下面是我的模块:

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

}

My Test

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

您应该注意以下事项:

  • 导入您的utils作为模块然后模拟callAnotherLambdaFunction功能

  • 模拟返回值callAnotherLambdaFunction with Resolve and Reject case https://jestjs.io/docs/en/mock-function-api.html#mockfnmockresolvedvaluevalue https://jestjs.io/docs/en/mock-function-api.html#mockfnmockresolvedvaluevalue

这是我的例子:

import testData from '../data.js';
import { handler } from '../src/index.js';
import * as Utils from '../../../utils'


jest.mock('../../../utils');
beforeAll(() => {
  Utils.callAnotherLambdaFunction = jest.fn().mockResolvedValue('test');
});

describe('>>> SEND EMAIL LAMBDA', () => {
  it('should return a good value', async () => {
    const callback = jest.fn()
    await handler(testData, null, callback);
    expect(callback).toBeCalledWith(null, {success: true, returnValue: 'test'})
  });
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JestJS - 尝试在 Node JS 测试中模拟 Async Await 的相关文章

随机推荐