gpt4 book ai didi

javascript - 在 Jest 中模拟 Lambda 回调? (无法读取未定义的属性体)

转载 作者:行者123 更新时间:2023-12-04 07:58:53 25 4
gpt4 key购买 nike

我正在尝试对 lambda 函数进行单元测试,但不知道如何模拟 lambda callback所以它停止代码执行。 callback我模拟被调用,在 lambda 的情况下会立即返回响应。但是,在我的单元测试中,它继续执行代码,但出现错误:

TypeError: Cannot read property 'body' of undefined
我对 Jest 比较陌生,所以不知道如何继续。 example.js ( lambda 代码)
// dependencies
const got = require('got');

// lambda handler
const example = async (event, context, callback) => {
// message placeholder
let message;

// set request options
const gotOptions = {
json: {
process: event.process
},
responseType: 'json'
};

// http response data
const res = await got.post('https://some.url/api/process', gotOptions).catch((error) => {
message = 'error calling process';

// log and return the error
console.log(message, error);
callback(message);
});

// res.body is causing the error in the test since
// this code still executes after callbacks triggered
message = `Process ${event.process} is: ${res.body.active}`;


callback(null, message);
};


// export example
exports.example = example;
example.test.js (单元测试代码)
// get the lib we want to test
const example = require('./example');

// setup mocks
jest.mock('got');

// mock our lambda callback
const callback = jest.fn();


// import the modules we want to mock
const got = require('got');


// set default event
let event = {
process: 1
};

// set default context
const context = {};


// run before each test
beforeEach(() => {
// set default got.post response
got.post.mockReturnValue(Promise.resolve({
body: {
active: true
}
}));
});

// test artifact api
describe('[example]', () => {
...other tests that pass...

test('error calling process api', async () => {
let error = 'error calling process';

// set got mock response for this test to error
got.post.mockReturnValue(Promise.reject(error));

// function we want to test w/ mock data
await example.example(event, context, callback);

// test our callback function to see if it matches our desired expectedResponse
expect(callback).toHaveBeenCalledWith(error);
});
});

最佳答案

您需要模拟 callback 的实现功能。为了在错误处理后停止执行代码,您需要throw new Error() ,并使用 await expect(example.example(event, context, callback)).rejects.toThrow(error);捕获错误以避免测试失败。这样我们就可以模拟 aws lambda 的行为了
例如。example.js :

const got = require('got');

const example = async (event, context, callback) => {
let message;

const gotOptions = {
json: {
process: event.process,
},
responseType: 'json',
};

const res = await got.post('https://some.url/api/process', gotOptions).catch((error) => {
callback(error);
});

console.log('process');
message = `Process ${event.process} is: ${res.body.active}`;

callback(null, message);
};

exports.example = example;
example.test.js :
const example = require('./example');
const got = require('got');

jest.mock('got');
const callback = jest.fn().mockImplementation((errorMsg) => {
if (errorMsg) throw new Error(errorMsg);
});
const event = { process: 1 };
const context = {};

describe('[example]', () => {
test('error calling process api', async () => {
let error = 'error calling process';
got.post.mockRejectedValueOnce(error);
await expect(example.example(event, context, callback)).rejects.toThrow(error);
expect(callback).toHaveBeenCalledWith(error);
});

test('should success', async () => {
got.post.mockResolvedValueOnce({
body: { active: true },
});
await example.example(event, context, callback);
expect(callback).toHaveBeenCalledWith(null, 'Process 1 is: true');
});
});
测试结果:
 PASS  examples/66567679/example.test.js
[example]
✓ error calling process api (5 ms)
✓ should success (10 ms)

console.log
process

at examples/66567679/example.js:17:11

------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
example.js | 100 | 100 | 100 | 100 |
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 3.966 s, estimated 4 s

关于javascript - 在 Jest 中模拟 Lambda 回调? (无法读取未定义的属性体),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66567679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com