and*_*dre 6 javascript unit-testing node.js jestjs aws-lambda
我正在尝试将 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})
}
Run Code Online (Sandbox Code Playgroud)
我的测试
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);
})
Run Code Online (Sandbox Code Playgroud)
您应该注意以下事项:
将您的导入utils为模块然后模拟callAnotherLambdaFunction
函数
callAnotherLambdaFunctionwithResolve和Rejectcase
的模拟返回值https://jestjs.io/docs/en/mock-function-api.html#mockfnmockresolvedvaluevalue
这是我的例子:
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'})
});
})
Run Code Online (Sandbox Code Playgroud)
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);
});
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
13108 次 |
| 最近记录: |