我正在尝试对 lambda 函数进行单元测试,但不知道如何模拟 lambda 上下文,以便在抛出错误时停止代码执行,jest 继续其单元测试。我已经尝试了一些事情,但代码继续执行或 Jest 抛出此错误:
FAIL api/lambda.unit-test.js
● lambda tests › Error
This is some mocked error
48 | // mock context implementation
49 | context.done.mockImplementation((error) => {
> 50 | throw new Error(error);
| ^
51 | });
52 |
53 | // function we want to test w/ mock data
at Object.<anonymous> (api/lambda.unit-test.js:50:13)
at foo (api/lambda.js:11:13)
at Object.<anonymous> (api/lambda.unit-test.js:54:29)
我目前拥有的代码如下,导致上述错误...
lambda
// dependencies
const { approle } = require('./libs/approle');
// lambda function
const foo = async (event, context) => {
const role = await approle();
// error retrieving approle?
if (role.error) {
// stop lambda execution and return our error
context.done(role.error);
}
return role.data;
};
// export our handler api modules
exports.foo = foo;
单元测试
// get the module we want to test
const { foo } = require('./lambda');
// mock modules
jest.mock('./libs/approle');
// import modules
const { approle } = require('./libs/approle');
// placeholder for mocking lambda context
let context;
beforeEach(() => {
// reset mocks
jest.resetAllMocks();
// mock lambda context
context = {
done: jest.fn(),
};
});
describe('lambda tests', () => {
test('Success', async () => {
// mock call to return error
approle.mockReturnValue({
data: 'some data'
});
// function we want to test w/ mock data
const moduleUnderTest = await foo({}, context);
// what we expect our moduleUnderTest to return
const expectedResponse = 'some data';
// test results
expect(moduleUnderTest).toEqual(expectedResponse);
expect(approle).toHaveBeenCalledTimes(1);
});
test('Error', async () => {
// mock call to return error
approle.mockReturnValue({
error: 'This is some mocked error'
});
// mock context implementation
context.done.mockImplementation((error) => {
throw new Error(error);
});
// function we want to test w/ mock data
const moduleUnderTest = await foo({}, context);
// what we expect our moduleUnderTest to return
const expectedResponse = 'This is some mocked error';
// test results
expect(moduleUnderTest).toEqual(expectedResponse);
expect(approle).toHaveBeenCalledTimes(1);
expect(() => { context.done(); }).toThrow(1);
});
});