簡體   English   中英

如何使用Jest和React測試功能

[英]How to Test a function with Jest and React

我是開玩笑和反應的新手,我需要為此功能編寫單元測試,我確實試圖理解文檔,但仍在努力了解如何准確模擬此功能?

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]); });
 });
});

如果需要對對象列表/數組進行排序,則應執行以下操作:

請注意,您的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); }); }); 

找到了一個解決方案,正如Dave所說的,我需要用數據調用它,然后檢查它是否匹配,

 describe('Tests for the descendingOrderBy function', () => {
it('should reverse the full and part contracts', () => {
    const ordering = desc(fullObject, partContract, 'title');
    expect(ordering).toEqual(-1);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM