Search code examples
javascriptunit-testingjasminestub

How to mock a request in jasmine


How do I mock the request in this function. I want to unit test this function using jasmine.

function getProducts() {
  return new Promise((resolve, reject) => {
    request.get(
      {
        url: 'http://ascott.com/products'
        
      },
      (err, response, body) => {
        if (err) return reject(err);
        const result = JSON.parse(body);
        if(result.value =='yes') return resolve(1);
        return resolve(0);
      }
    );
  });
}

Solution

  • Use spyOn(obj, methodName) function to install a spy onto request.get() method, then use callFake(fn) tell the spy to call a fake implementation when invoked. So that you can trigger the callback in the fake implementation.

    index.js:

    import request from 'request';
    
    export function getProducts() {
      return new Promise((resolve, reject) => {
        request.get({ url: 'http://ascott.com/products' }, (err, response, body) => {
          if (err) return reject(err);
          const result = JSON.parse(body);
          if (result.value == 'yes') return resolve(1);
          return resolve(0);
        });
      });
    }
    

    index.test.js:

    import { getProducts } from '.';
    import request from 'request';
    
    describe('69769551', () => {
      it('should return 1', async () => {
        spyOn(request, 'get').and.callFake((_, callback) => {
          callback(null, null, JSON.stringify({ value: 'yes' }));
        });
        const actual = await getProducts();
        expect(actual).toEqual(1);
      });
    
      it('should throw error', async () => {
        const mError = new Error('network');
        spyOn(request, 'get').and.callFake((_, callback) => {
          callback(mError);
        });
        await expectAsync(getProducts()).toBeRejectedWithError('network');
      });
    });
    

    test result:

    Executing 2 defined specs...
    Running in random order... (seed: 04537)
    
    Test Suites & Specs:
    
    1. 69769551
       ✔ should throw error (7ms)
       ✔ should return 1 (1ms)
    
    >> Done!
    
    
    Summary:
    
    👊  Passed
    Suites:  1 of 1
    Specs:   2 of 2
    Expects: 2 (0 failures)
    Finished in 0.017 seconds
    

    package versions:

    "jasmine": "^3.6.3"
    "request": "^2.88.2"