gpt4 book ai didi

javascript - 我如何对 JavaScript 中 promise 的 'then' 结果进行单元测试?

转载 作者:行者123 更新时间:2023-11-30 11:09:01 25 4
gpt4 key购买 nike

我正在使用 TypeScript 编写一个非常简单的服务,该服务利用了 AWS 开发工具包。我的 Jest 单元测试通过了,但是覆盖率报告说“return result.Items”这一行没有被覆盖。谁能说出这是为什么?这是 Jest 错误吗?

// service file

/**
* Gets an array of documents.
*/
function list(tableName) {
const params = {
TableName: tableName,
};
return docClient
.scan(params)
.promise()
.then((result) => {
return result.Items;
});
}

// test file

const stubAwsRequestWithFakeArrayReturn = () => {
return {
promise: () => {
return { then: () => ({ Items: 'fake-value' }) };
},
};
};

it(`should call docClient.scan() at least once`, () => {
const mockAwsCall = jest.fn().mockImplementation(stubAwsRequest);
aws.docClient.scan = mockAwsCall;
db.list('fake-table');
expect(mockAwsCall).toBeCalledTimes(1);
});

it(`should call docClient.scan() with the proper params`, () => {
const mockAwsCall = jest.fn().mockImplementation(stubAwsRequest);
aws.docClient.scan = mockAwsCall;
db.list('fake-table');
expect(mockAwsCall).toBeCalledWith({
TableName: 'fake-table',
});
});

it('should return result.Items out of result', async () => {
const mockAwsCall = jest
.fn()
.mockImplementation(stubAwsRequestWithFakeArrayReturn);
aws.docClient.get = mockAwsCall;
const returnValue = await db.get('fake-table', 'fake-id');
expect(returnValue).toEqual({ Items: 'fake-value' });
});

最佳答案

未覆盖的行是传递给 then 的成功回调。

您的模拟将 then 替换为不接受任何参数且仅返回一个对象的函数。来自您代码的回调在测试期间被传递给 then 模拟,但它不会调用回调,因此 Jest 正确地报告回调未被您的测试覆盖。

与其尝试返回一个看起来Promise的模拟对象,不如从您的模拟中返回一个实际解析的Promise:

const stubAwsRequestWithFakeArrayReturn = () => ({
promise: () => Promise.resolve({ Items: 'fake-value' })
});

...这样 then 仍然是实际的 Promise.prototype.then并且您的回调将按预期调用。


您还应该await 返回的Promise 以确保在测试完成之前调用回调:

it(`should call docClient.scan() at least once`, async () => {
const mockAwsCall = jest.fn().mockImplementation(stubAwsRequest);
aws.docClient.scan = mockAwsCall;
await db.list('fake-table'); // await the Promise
expect(mockAwsCall).toBeCalledTimes(1);
});

it(`should call docClient.scan() with the proper params`, async () => {
const mockAwsCall = jest.fn().mockImplementation(stubAwsRequest);
aws.docClient.scan = mockAwsCall;
await db.list('fake-table'); // await the Promise
expect(mockAwsCall).toBeCalledWith({
TableName: 'fake-table',
});
});

关于javascript - 我如何对 JavaScript 中 promise 的 'then' 结果进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54500259/

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