【问题标题】:How do you stub fetch api request你如何存根获取 api 请求
【发布时间】:2017-06-05 13:07:41
【问题描述】:

我在使用 fetch 的存根/测试函数时遇到问题。

使用简单的例子:

export const clickTimeseries => {
  return fetch('...url...')
    .then(response => {
      if(response.status == 200)
        return response.json()
      else
        throw 'something'
    })
    .then(json => {
      return {
        success: true,
        data: json,
      }
    })
    .catch(err => {
      return {
        success: false,
        error: err,
      }
    })
}

我的测试:

import { expect } from 'chai'
import sinon from 'sinon' 

import Promise from 'es6-promise' 
Promise.polyfill() 

import 'whatwg-fetch'

import clickTimeseries from './above'

const jsonOK = body => {  
  const mockResponse = new Response(JSON.stringify(body), {  
    status: 200,
    headers: { 
      'Content-type': 'application/json'
    }
  })

  return Promise.resolve(mockResponse) 
}

describe('APIs', () => {  
  describe('Click timeseries', () => { 
    it('builds a correct data on success', () => { 
      sinon.stub(window, 'fetch').returns(jsonOK({stuff: [1,2,3]})) 

      expect(clickTimeseries()).to.eq({ 
        success: true,
        data: {stuff: [1,2,3]}
      })
    })
  })
})

我收到错误:

expected { Object (, _state, ...) } to equal { success: true, data: {stuff: [ 1, 2, 3, 4 ] }}

看起来spendTimeseries 返回了promise,而不是调用两个then 块的结果。

你必须如何设置你的测试才能让它通过?

【问题讨论】:

    标签: javascript sinon fetch-api


    【解决方案1】:

    我花了一些时间处理您的代码,直到我意识到出了什么问题,因为一切看起来都是正确的。事实上,确实如此。除了一件事:您正在测试的结果是异步交付的,但您正在同步测试它。这意味着您需要将测试更改为异步。

    我假设您使用 Mocha 作为测试运行程序,它有两种测试异步代码的方法。任何异步代码的一种标准方式,以及一种处理 Promise 的特殊方式。你可以使用任何适合你的风格。

    如果您有任何异步代码在稍后交付结果,这是通用公式:

    it('should test an async function', (callback) => {
        const expectedResult = 42;
        doSomethingAsync((result) => {
            try{
                expect(expectedResult).to.equal(result);
                callback();
            } catch(err) {
                callback(err);
            }
        })
    });
    

    对于一个 promise 返回函数,它看起来像这样:

    it('should test a promise', (callback) => {
        const expectedResult = 42;
        doSomethingAsync().then((result) => {
            expect(expectedResult).to.equal(result);
            callback();
        }).catch(callback);
    });
    

    Mocha 为 promise 提供了一些糖分,可以像这样编写最后一个函数(函数包装器中没有回调!):

    it('should test a promise', () => {
        const expectedResult = 42;
        return doSomethingAsync().then((result) => {
            expect(expectedResult).to.equal(result);
        })
    });
    

    结论:只需将测试更改为如下所示:

    return clickTimeseries().then( result => {
        expect(result).to.eq({ 
            success: true,
            data: {stuff: [1,2,3]}
        })
    })
    

    【讨论】:

    • 感谢您的宝贵时间!看准队友。
    • 你让sinon上班了吗?这是sinon.stub(window, 'fetch'),我似乎无法开始工作......错误是“TypeError:无法存根不存在的自己的属性获取”......
    • @carpediem 提交一个单独的问题。如果您希望我查看它,请使用 URL ping 此处。诗乃工作正常。
    • @carpiediem 将 window 替换为 global
    猜你喜欢
    • 2016-03-16
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    相关资源
    最近更新 更多