0
votes

I have a React Component which calls a method from another module.
The module just returns 1 method:

export default (url, method, authorization, body) => {
  const headers = { 'Content-Type': 'application/json' }
  if (authorization) headers.Authorization = localStorage.getItem('id_token');
  return fetch(url, {
    method,
    headers,
    body: JSON.stringify(body)
  }).then(res => res.json());
}

I'd like to mock this method/module, so the real code doesn't get called when testing the Components using it.
I'm a novice at React/Jest/Enzyme so I could be missing something easy.

In my test file:

jest.mock('../../utils/fetch.js', () => () => {
  Promise.resolve({_id: 1});
});
import fetch from '../../utils/fetch';

Where the method is used:

return fetch('/api/items', 'post', true, newItem).then(res => {
  this.props.history.push(`/items/${res._id}`);
}).catch(console.log);
1

1 Answers

1
votes

So you have a module that returns a function that will be return a promise. If you only want to test the happy path just return a resolved promise from your mock:

jest.mock('./my-function.js', () => () => Promise.resolve('foo'));

if you need to set the result of the function during your test mock the module with a spy and set the result later on in your test:

jest.mock('./my-function.js', () => jest.fn());
import myFunction from './my-function.js'
describe('foo',()=>{
  it('the happy pass',()=> {
     myFunction.mockImplementation(() => Promise.resolve('foo'))
    //your assertion here 
  })

  it('when it fails',()=> {
     myFunction.mockImplementation(() => Promise.reject())
     //your assertion here 
  })
})
})

Note that you have to mock it on top of the module. Otherwise you will have the original imported and later on replace the module with the mock, which will have no effect on the imported on. Think of mocking as a way to say jest how to resolve an import. So mocking something after importing it will have no effect.