[英]Unit Test case for Sorting in Jest
I am new to reactjs and jest.我是 reactjs 的新手,开玩笑。 I am trying to write a test case that will pass the sort function written in container.
我正在尝试编写一个测试用例,它将通过容器中编写的 function 排序。 I am not sure how to write it.
我不知道怎么写。
I am getting TypeError: Cannot read property 'sort' of undefined
error when I try to run the test case.当我尝试运行测试用例时,出现
TypeError: Cannot read property 'sort' of undefined
错误。
Actual Array实际数组
let testArray=[{trackingId:'1',updated: '1512885243'},
{trackingId:'1',updated: '1512485253'},
{trackingId:'3',updated: '1512884233'},
{trackingId:'2',updated: '1512885243'}];
Expected Array预期数组
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))
});
Sort function in my container class for which I am writing the unit test:在我正在为其编写单元测试的容器 class 中对 function 进行排序:
customerTrackingInfo = customerTrackingInfo.sort( (a,b) => {
if (a.trackingId !== b.trackingId) {
return a.trackingId - b.trackingId;
}
return new Date(b.updated) - new Date(a.updated);
});
I like how elegant @Rafał Figura's answer is, but it has one one major flaw, which is that even though Array.prototype.sort() returns a sorted array, it sorts the original array in place , mutating it.我喜欢@Rafał Figura 的回答多么优雅,但它有一个主要缺陷,即即使Array.prototype.sort()返回一个排序数组,它也会对原始数组进行排序,改变它。 This means that
这意味着
expect(array).toStrictEqual(array.sort(sortingFunction))
will always pass since array.sort(sortingFunction)
will update array
to be the sorted value.将始终通过,因为
array.sort(sortingFunction)
会将array
更新为排序后的值。 The fix is simple, though.不过,修复很简单。 Just copy the array before sorting it:
只需在排序之前复制数组:
expect(array).toStrictEqual([...array].sort(sortingFunction))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.