Reputation: 11
I am new to react and not able to find how can i get the code coverage done for my below mentioned function using jest.
For the sake of clarity I have created a function just similar to what I am using :
setName: function setName () {
var storage = localStorage.getItem(user);
var session = sessionStorage.getItem(temp);
if ((session === null || session === undefined) && (storage === null && storage === undefined)) {
var name = "window.name";
if (name === 'John') {
changeName(name);
} else if (name === 'Jane') {
changeName(name);
} else if (name === 'Mark') {
changeName(name);
} else {
changeName('John');
}
} else if (session !== null) {
changeName(session);
} else if (storage !== null) {
changeName(storage);
}
}
Any help is appreciated
Upvotes: 0
Views: 16299
Reputation: 11250
You need to be able to specify the name 'John', 'Jane', etc. To do this with your sample you will need to save the appropriate data into localStorage and sessionStorage before running the test.
In your test file:
localStorage.setItem('John');
sessionStorage.setItem('A Session');
// do the test now and test what you expect to get back when the user is John.
localStorage.setItem('Jane');
// do the test now and test what you expect to get back when the user is Jane.
The tests could be done with a loop and arrays if the results being tested for are basic and you can simply do a foreach or similar.
testData = [
{ Name: 'John', Result: true},
{ Name: 'Jane', Result: false}
];
testData.forEach(function(testItem) {
expect(setName(testItem.Name)).toBe(testItem.Result);
}
Another option is to move the access to local and session storage out of your function setName() and then use dependency injection or other functions in your code to get these values. Then you can set up a mock (or dummy function) for returning the data for the storage which returns hard set literal data to test each part of the if() structure.
Upvotes: 1