Unit test of a javascript fetch function with jest or mocha

1

I'm starting TDD studies and came across a function like this:

const fetchexample = callback => {
  fetch('/token', {
    method: 'POST',
    body: 'user=teste'
  }).then(res => res.json()).then(json => {
    localStorage.setItem('token', json.access_token)
  }).then(() => callback())
}

But my question is how would we test this function? Since it makes an asynchronous request and I have never worked with this type of test for this type of request? Would anyone have any examples about the subject or article?

    
asked by anonymous 09.11.2017 / 12:56

1 answer

1

The it gets two arguments. The description and function to run the test. This function can pass an argument, which is a function to execute when the test is finished. It would look like this:

const fetchexample = callback => {
  fetch('/token', {
    method: 'POST',
    body: 'user=teste'
  }).then(res => res.json()).then(json => {
    localStorage.setItem('token', json.access_token)
  }).then(() => callback())
}
it('should test async code', function(done){
  fetchexample(done);
});

Another way to make the API available is to return a promise. but in this case since it's a callback function that you want to test the done is more practical.

Jest Docs on Asynchronous Tests: link

    
09.11.2017 / 13:04