-1

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
      })
    })
Anand Deep Singh
  • 2,560
  • 3
  • 22
  • 28
  • Why are you creating mocks to pass as the `.then`/`.catch` callbacks at all? Use https://jestjs.io/docs/asynchronous#resolves--rejects. Also note `mockResponseONce` looks like a typo - can you give a [mre] of the the actual setup? – jonrsharpe Jul 15 '21 at 13:51

1 Answers1

0

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();
Pushpendu
  • 159
  • 10
  • Thanks Pushpendu, I have already setup fetchMock as you mentioned in last code example. The thing is I am able to use fetchMock in my test file but still not able to mock the service :( – Anand Deep Singh Jul 16 '21 at 02:31
  • Could you try and put a catch block at the end of fetch().then().then()? Log whatever error is coming there. That might help understand the issue better – Pushpendu Jul 16 '21 at 03:01
  • then its calling my actual API and return error object which I defined i.e., { response: null, error: 'Error'} – Anand Deep Singh Jul 16 '21 at 03:05
  • This might seem like a shot in dark, but could you try to enable jest-fetch-mock for this specific test file? require('jest-fetch-mock').enableMocks(); right below your import statments – Pushpendu Jul 16 '21 at 03:21
  • So I tried your exact code, and only thing that seemed out of place was that instead of data.response you should be checking data.data.response for if condition to return the accesstoken part. Apart from that it worked perfectly for me. I'll try to create a working example probably on stackblitz – Pushpendu Jul 16 '21 at 03:33
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/234946/discussion-between-anand-deep-singh-and-pushpendu). – Anand Deep Singh Jul 16 '21 at 04:12