I'm testing this reducer:
const todo = (state = {}, action) => {
switch(action.type) {
case 'ADD_TODO':
return {
id: action.id,
text: action.text,
completed: false
}
case 'TOGGLE_TODO':
if(state.id !== action.id) {
return state;
}
return {...state, completed: !state.completed};
default:
return state;
}
}
const todos = (state = [], action) => {
switch(action.type) {
case 'ADD_TODO':
return [
...state,
todo(undefined, action)
]
case 'TOGGLE_TODO':
return state.map(item => todo(item, action));
default:
return state;
}
}
export default todos;
With this test:
import todos from './todos';
test('creates a new todo', () => {
const stateBefore = [];
const action = {
type: 'ADD_TODO',
id: 0,
text: 'test'
};
const stateAfter = [{
id: 0,
text: 'test',
completed: false
}];
expect( JSON.stringify( todos(stateBefore, action) ) ).toBe( JSON.stringify(stateAfter) );
});
The problem is that my tests fail with a Compared values have no visual difference
remark if I remove the JSON.stringify()
calls - I get that comparing an object to an object poses some problems because of reference, but do I have to use JSON.stringify()
or loop through the object keys to compare them each time?
Despite what many may think, Jest is not just a test runner—it is a complete testing framework that has brought testing to another level. It's powerful but easy to use, so give it a try.
As a result Cypress provides better, faster, and more reliable testing for anything that runs in a browser. Cypress works on any front-end framework or website. What is Jest? Painless JavaScript Unit Testing.
Jest typically expects to execute the tests' functions synchronously. If we do an asynchronous operation, but we don't let Jest know that it should wait for the test to end, it will give a false positive.
so to test this function you need to provide some input and expect an output. So you could write a test like this: describe('extractInfo', () => { test('test 1', () => { //inputs const Info = ''; const description = ''; const jestinformation = ''; //test const result = extractInfo(Info); //expect expect(result).
I'm answering my own question.
The .toBe
method tests for exact (===
) equality. In order to compare objects, you have to use the .toEqual
method which does recursive checks of every object key / array index, depending on your data type.
In conclusion, you don't have to use JSON.stringify()
and Jest goes through object keys for you, you just have to use the right equality testing method.
Source: https://facebook.github.io/jest/docs/using-matchers.html#content
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With