我对开玩笑和反应不熟悉,我需要为此功能编写单元测试,我确实试图理解文档,但是我在努力理解如何准确模拟此功能?
function desc(a, b, orderBy) {
if (b[orderBy] < a[orderBy]) {
return -1;
}
if (b[orderBy] > a[orderBy]) {
return 1;
}
return 0;
}
这也是我开玩笑的测试,该测试通过了,但是没有断言或行覆盖率
describe('Contract Table Ordering', () => {
it('orders by desc', () => {
contract.desc.mockImplementation(async () => { return (a, b, orderBy)
=> (a[orderBy] > b[orderBy]) - (a[orderBy] < b[orderBy]); });
});
});
答案 0 :(得分:0)
如果需要对对象列表/数组进行排序,则应执行以下操作:
请注意,您的js文件(sortFn.js)和单元测试文件(sortFn.js)应位于同一文件夹中。
//in your js (sortFn.js) file:
const sortTable = orderBy => {
return function(a, b) {
if (a[orderBy] > b[orderBy]) {
return -1;
} else if (a[orderBy] < b[orderBy]) {
return 1;
}
return 0;
};
}
export default sortTable;
//In your unit-test file (sortFn.test.js):
import sortTable from './sortFn';
describe('Contract Table Ordering', () => {
const originalArray = [{name: 'ab', age: 19}, {name: 'xz', age: 26}, {name: 'ab', age: 14}, {name: 'cw', age: 22}];
const expectedArray = [{name: 'xz', age: 26}, {name: 'cw', age: 22}, {name: 'ab', age: 19},{name: 'ab', age: 14}];
it('orders by desc', () => {
const sortResult = originalArray.sort(sortTable('age'));
expect(sortResult).toEqual(expectedArray);
});
});
答案 1 :(得分:0)
找到了一个解决方案,正如戴夫所说,我需要用数据调用它,然后检查它是否匹配,
describe('Tests for the descendingOrderBy function', () => {
it('should reverse the full and part contracts', () => {
const ordering = desc(fullObject, partContract, 'title');
expect(ordering).toEqual(-1);
});