简体   繁体   English

AWS lambda 的笑话单元测试

[英]jest unit test for AWS lambda

I am new to Node.js.我是 Node.js 的新手。 I was trying to write a jest unit test cases for AWS lambda function(for node environment).我试图为 AWS lambda 函数(用于节点环境)编写一个开玩笑的单元测试用例。 I used a node module called "lambda-tester" to test it.我使用了一个名为“lambda-tester”的节点模块来测试它。 But the problem with "lambda-tester" is, it will hit the actual service and return the data.但是“lambda-tester”的问题是,它会命中实际的服务并返回数据。 I don't want to do that.我不想那样做。 I need to mock the service call.我需要模拟服务调用。

So, I wanted to go with the plain old way.所以,我想用普通的旧方式 go 。 But, I have issues with mocking it.但是,我对 mocking 有疑问。 Can you help me to write basic unit test case for the below lambda ith mocking the function "serviceFunction"?你能帮我为下面的 lambda 和 mocking function "serviceFunction" 编写基本单元测试用例吗?

const dataService = require('../dataService');

exports.lambdaService = async event => {
  let response = await serviceFunction(event.id);
  if (response.code == 200) {
    return response;
  } else {
    return {
      statusCode: response.code,
      body: JSON.stringify({
        message: response.message
      })
    };
  }
};

const serviceFunction = async id => {
  return await dataService.retrieveData(id);
};

You can use jest.spyOn(object, methodName, accessType?) method to mock dataService.retrieveData method.您可以使用jest.spyOn(object, methodName, accessType?)方法来模拟dataService.retrieveData方法。 And, your serviceFunction function only has one statement, so you can test lambdaService function with it together.而且,你的serviceFunction function 只有一个语句,所以你可以一起测试lambdaService function 。

Eg例如

index.js : index.js

const dataService = require('./dataService');

exports.lambdaService = async event => {
  let response = await serviceFunction(event.id);
  if (response.code == 200) {
    return response;
  } else {
    return {
      statusCode: response.code,
      body: JSON.stringify({
        message: response.message
      })
    };
  }
};

const serviceFunction = async id => {
  return await dataService.retrieveData(id);
};

dataService.js : dataService.js

module.exports = {
  retrieveData: async id => {
    return { code: 200, data: 'real data' };
  }
};

index.spec.js : index.spec.js

const { lambdaService } = require('.');
const dataService = require('./dataService');

describe('lambdaService', () => {
  beforeEach(() => {
    jest.restoreAllMocks();
  });
  test('should return data', async () => {
    const mResponse = { code: 200, data: 'mocked data' };
    const mEvent = { id: 1 };
    const retrieveDataSpy = jest.spyOn(dataService, 'retrieveData').mockResolvedValueOnce(mResponse);
    const actualValue = await lambdaService(mEvent);
    expect(actualValue).toEqual(mResponse);
    expect(retrieveDataSpy).toBeCalledWith(mEvent.id);
  });

  test('should return error message', async () => {
    const mResponse = { code: 500, message: 'Internal server error' };
    const mEvent = { id: 1 };
    const retrieveDataSpy = jest.spyOn(dataService, 'retrieveData').mockResolvedValueOnce(mResponse);
    const actualValue = await lambdaService(mEvent);
    expect(actualValue).toEqual({ statusCode: 500, body: JSON.stringify({ message: mResponse.message }) });
    expect(retrieveDataSpy).toBeCalledWith(mEvent.id);
  });

  test('should throw an error', async () => {
    const mEvent = { id: 1 };
    const retrieveDataSpy = jest.spyOn(dataService, 'retrieveData').mockRejectedValueOnce(new Error('network error'));
    await expect(lambdaService(mEvent)).rejects.toThrowError(new Error('network error'));
    expect(retrieveDataSpy).toBeCalledWith(mEvent.id);
  });
});

Unit test result with coverage report:带有覆盖率报告的单元测试结果:

 PASS  src/stackoverflow/58623194/index.spec.js
  lambdaService
    ✓ should return data (6ms)
    ✓ should return error message (4ms)
    ✓ should throw an error (2ms)

----------------|----------|----------|----------|----------|-------------------|
File            |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------------|----------|----------|----------|----------|-------------------|
All files       |       90 |      100 |    66.67 |       90 |                   |
 dataService.js |       50 |      100 |        0 |       50 |                 3 |
 index.js       |      100 |      100 |      100 |      100 |                   |
----------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        4.619s

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58623194源码: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58623194

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM