如何在茉莉花中模拟请求

How to mock a request in jasmine

如何在此函数中模拟请求。我想使用 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);
      }
    );
  });
}

使用 spyOn(obj, methodName) 函数将间谍安装到 request.get() 方法上,然后使用 callFake(fn) 告诉间谍在调用时调用伪造的实现。这样你就可以在假实现中触发回调。

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');
  });
});

测试结果:

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

包版本:

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