Unit test using jest spy and mock implementation
Jest is widely used as a testing framework. Unit test is good opportunity for a developer to test their code.
While writing unit test there are many challenges that we face and one such thing is we have a method and it returns multiple results based on the request/input.
It is very difficult when we have this setup and we want to cover all the lines and different scenarios.
Jest provides certain methods which can help us to achieve different results.
Let's directly dive into the code.
I have a sample class with the following code
export class Test {
getA(value: Number): string {
return value===1 ? 'test' : 'no';
}
}
For this we can write unit test like
jest.spyOn(Test.prototype, 'getA').mockImplementation((argument) => {
if(argument === '1'){
return 'test';
} else {
return 'no'
}
});
This way we can spyOn certain methods and return based on the request argument.
This will help us to cover all the lines and different test cases.
No comments:
Post a Comment
If you have any doubts, Please let me know