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

标签 javascript node.js unit-testing aws-lambda jestjs

我正在尝试使用 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})

}

我的测试

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

最佳答案

您应该注意以下事项:

这是我的例子:

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

关于javascript - JestJS - 尝试在 Node JS 测试中模拟 Async Await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45168803/

相关文章:

javascript - Meteor 动态 MongoDB 集合

c# - Microsoft Shims 无法调试正在测试的方法

javascript - 将路由和导航样式与 AngularJS 关联起来

javascript - 如何确定文件是否下载成功

node.js - 我正在尝试使用 Express 和 Passport 创建一个 nodejs 登录系统,但出现错误

node.js - Node Async forEach - 如何通过键而不是值进行迭代

java - 是否有使用 Groovy 进行单元测试(以及集成或回归,如果适用)的情况?

c++ - 托管测试项目和 native 单元测试项目之间的 Visual Studio C++ 区别

javascript - D3 JS - 时间轴上的刻度间距被月份边界弄乱了

javascript - 如何在 Javascript/HTML 中保持重定向时的滚动位置