Reputation: 2620
I am calling an API using fetch and writing test cases for that. While making the Fetch call, I am expected mocked data but getting API error message.
Please help me to know why its not mocking the data.
Using Jest, jest-fetch-mock modules. Code is as follow
const login = (username, password) => {
return fetch('endpoint/login', () => {
method: 'POST',
body: JSON.stringify({
data :{
username,
password
}
})
})
.then (res => res.json())
.then (data => {
if(data.response){
return {
response: "accessToken",
error: null
}
}else{
return {
response: null,
error: "Something went wrong"
}
}
})
}
Now I am writing Unit Test to test this api, as below :-
test("Auth Success Scenario", async () => {
const onResponse = jest.fn();
const onError = jest.fn();
fetchMock.mockResponseONce(JSON.stringify({
data: {
response: "accessToken",
error: null
}
}));
return await AuthService.login("andy","password")
.then(onResponse)
.catch(onError)
.finally( () => {
console.log(onResponse.mock.calls[0][0]) // its return API error not mocked data
})
})
Upvotes: -1
Views: 2707
Reputation: 169
It was meant to be comment, sadly I don't have enough reputation.
Have you enabled jest mocks as specified in the documentation link
Create a setupJest file to setup the mock or add this to an existing setupFile. :
To setup for all tests
require('jest-fetch-mock').enableMocks()
Add the setupFile to your jest config in package.json:
"jest": {
"automock": false,
"setupFiles": [
"./setupJest.js"
]
}
Because that seems to be the only case, in which fetch will try to make actual call to the API, instead of giving mocked response, thus causing failure.
You can even enable mocks for specific test file as well
import fetchMock from "jest-fetch-mock";
require('jest-fetch-mock').enableMocks();
Upvotes: 0