gpt4 book ai didi

javascript - 在 Jest 中排序的单元测试用例

转载 作者:行者123 更新时间:2023-12-05 04:08:07 40 4
gpt4 key购买 nike

我是 reactjs 和 jest 的新手。我正在尝试编写一个测试用例,它将通过容器中编写的排序函数。不知道怎么写。

当我尝试运行测试用例时,出现了 TypeError: Cannot read property 'sort' of undefined 错误。

实际数组

let testArray=[{trackingId:'1',updated: '1512885243'},
{trackingId:'1',updated: '1512485253'},
{trackingId:'3',updated: '1512884233'},
{trackingId:'2',updated: '1512885243'}];

预期数组

let sortedArray = [{trackingId: '1', updated: '1512885243'},
{trackingId: '1', updated: '1512885253'},
{trackingId: '2', updated: '1512885243'},
{trackingId: '3', updated: '1512884233'}]

// I am thinking something like:
describe('Sorting', () => {
it('Array should be sortedby trackingId', () => {
testArray.sort((a,b) => {
if (a.trackingId !== b.trackingId) {
return a.trackingId - b.trackingId;
}
return new Date(b.updated) - new Date(a.updated);
});
expect(component.contains(result))
.toEqual(expect.arrayContaining(sortedArray))

});

我正在为其编写单元测试的容器类中的排序函数:

customerTrackingInfo = customerTrackingInfo.sort( (a,b) => {
if (a.trackingId !== b.trackingId) {
return a.trackingId - b.trackingId;
}
return new Date(b.updated) - new Date(a.updated);
});

最佳答案

我喜欢@Rafał Figura 的优雅回答,但它有一个主要缺陷,即即使 Array.prototype.sort()返回一个已排序的数组,它将原始数组就地排序,并对其进行变异。这意味着

expect(array).toStrictEqual(array.sort(sortingFunction))

将始终通过,因为 array.sort(sortingFunction) 会将 array 更新为排序后的值。不过,修复很简单。只需在排序之前复制数组:

expect(array).toStrictEqual([...array].sort(sortingFunction))

关于javascript - 在 Jest 中排序的单元测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47935246/

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