Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
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);
      }
    );
  });
}
about 4 years ago ยท Juan Pablo Isaza
1 answers
Answer question

0

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"
about 4 years ago ยท Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!