Unit test of a javascript fetch function with jest or mocha

Asked

Viewed 339 times

2

I’m starting studies with TDD 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 that function? Since she does an asynchronous requisition and I’ve never worked with this kind of test for this kind of requisition? Would anyone have any example on the subject or article?

1 answer

2


The it takes two arguments. The description and function to run the test. This function can pass an argument, which is a function to run when the test is over. 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 that the API also provides is to return a file. but in this case since it is a callback function you want to test the done is more practical.

Jest’s Docs on Asynchronous Testing: https://facebook.github.io/jest/docs/en/asynchronous.html

  • Thank you @Sergio basically did what you told me. I also added a lib to help me by simulating fetch so I could test the actual function.

  • 1

    @Great! Jest is a very good library, I’m glad to have helped.

  • @Edmo if the answer solved your problem can mark as accepted

Browser other questions tagged

You are not signed in. Login or sign up in order to post.