javascriptreactjsunit-testinghttpintern

Unit testing http methods (get, post) in react / javascript using intern


This is my first time writing unit tests - please be nice.

I am trying to write unit tests for two functions. one function is to GET a number from the api, and the other is to POST data.

I am not sure how to do this. I know, I want to use the intern "expect" call and fetch-mock but the rest I want to do in react / javascript. I made a mock response with some data.

My questions are:

  1. How can I use fetch-mock to compare my expected output with what my function is outputting
  2. How does my mock response data relate to fetch-mock?

Again, I have not done this before and i am having a hard time understanding the resources available online (have been researching this for 8+ hours) so i am looking for another opinion


Solution

  • I haven't used fetch-mock before, and there are many ways to go about something like this, but the general process for mocking is to setup the mock, do what you need to do, and tear it down in an after or afterEach. How you actually go about checking whether your GET request worked depends on how you go about making the request in the first place.

    A test for a mock request might look something like this. The assumption here is that you have a request method that makes a request and returns a Promise (what you'd get if you did return fetch('some_url')).

    import * as fetchMock from 'fetch-mock';
    const { describe, it, afterEach } = intern.getPlugin('interface.bdd');
    const { expect } = intern.getPlugin('chai');
    
    describe('my suite', () => {
      afterEach(() => {
        fetchMock.restore();
      });
    
      it('should do something', () => {
        fetchMock.get('*', { hello: 'world' });
        return thingThatDoesAGetRequest.then(response => {
          expect(response).to.equal({ hello: 'world' });
        });
      })
    });
    

    Another option would be to wait for the mock request to complete rather than looking at a function return value:

    it('should do something', test => {
      // Create a promise that will resolve when a request is made
      const promise = new Promise(resolve => {
        fetchMock.get('*', () => {
          resolve();
          return { hello: 'world' }
        });
      });
    
      // Do whatever should be making a call
      thingThatDoesAGetRequest();
    
      // Wait for the request promise to resolve, then see if whatever
      // you expect to happen has happened
      return promise.then(() => {
        expect(something).to.equal({ hello: 'world' });
      });
    })