【问题标题】:How to mock a request in jasmine如何在茉莉花中模拟请求
【发布时间】:2021-12-14 13:38:38
【问题描述】:

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

【问题讨论】:

    标签: javascript unit-testing jasmine stub


    【解决方案1】:

    使用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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 2016-11-01
      • 1970-01-01
      相关资源
      最近更新 更多