开玩笑 - 尝试在节点Js测试中模拟异步等待

时间:2017-07-18 13:52:18

标签: javascript node.js unit-testing aws-lambda jest

我正在尝试将Jest用于我的Node Js测试(特别是AWS的Lambda),但我很难模拟异步等待功能。

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

关于如何实现这一点的任何想法?

以下是我的模块:

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

2 个答案:

答案 0 :(得分:2)

您应该注意以下几点:

这是我的示例:

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

答案 1 :(得分:0)

Load很好,但你实际上并没有嘲笑实现,你必须自己实现这个行为。

所以你需要添加

jest.mock('../../../utils');

希望这有帮助。

相关问题