How to Test a function with Jest and React

问题: I am new to jest and react and I need to write a unit test for this function, I have really tried to understand the documentation but I'm struggling to understand how I can...

问题:

I am new to jest and react and I need to write a unit test for this function, I have really tried to understand the documentation but I'm struggling to understand how I can accurately mock this function?

function desc(a, b, orderBy) {
if (b[orderBy] < a[orderBy]) {
    return -1;
}
if (b[orderBy] > a[orderBy]) {
    return 1;
}
return 0;
}

Also below this is my jest test which passes but has no assertions or line coverage

describe('Contract Table Ordering', () => {
 it('orders by desc', () => {
     contract.desc.mockImplementation(async () => { return (a, b, orderBy) 
=> (a[orderBy] > b[orderBy]) - (a[orderBy] <  b[orderBy]); });
 });
});

回答1:

If you need to sort a list/array of objects, you should do something like this:

Note that your both js file(sortFn.js) and unit-test file (sortFn.js) should be in the same folder.

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


回答2:

Found a solution, as Dave said i needed to call it with data and then check if it matches,

 describe('Tests for the descendingOrderBy function', () => {
it('should reverse the full and part contracts', () => {
    const ordering = desc(fullObject, partContract, 'title');
    expect(ordering).toEqual(-1);
});
  • 发表于 2019-03-01 19:00
  • 阅读 ( 225 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除