Reputation: 541
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]); });
});
});
Upvotes: 1
Views: 1628
Reputation: 541
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);
});
Upvotes: 1
Reputation: 301
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);
});
});
Upvotes: 2