【问题标题】:JestJS - Trying to Mock Async Await in Node JS TestsJestJS - 尝试在 Node JS 测试中模拟异步等待
【发布时间】:2017-12-23 10:35:03
【问题描述】:

我正在尝试将 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);
})

【问题讨论】:

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


    【解决方案1】:

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

    希望这会有所帮助。

    【讨论】:

    • 感谢您的及时回复。我试过了,得到以下错误:测试套件无法运行。 TypeError: _callAnotherLambdaFunction2.default.mockImplementation 不是函数
    • 你的函数应该是callAnotherFunction,因为这是你要模拟的函数。不确定callAnotherLambdaFunction 是什么,我在实际文件中没有看到
    • 是的,这是我在这个简化示例中的一个错字。实测中,函数处处同名
    【解决方案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'})
      });
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 2014-05-21
      • 2018-02-13
      • 2014-12-01
      • 2019-06-30
      • 2016-04-26
      相关资源
      最近更新 更多