2017-06-05 43 views
0

我有一個問題,使用提取的存根/測試功能。你如何存根提取API請求

使用簡單的例子:

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回報的承諾,呼叫then塊。

您將如何設置測試才能通過測試?

回答

3

花了一段時間玩你的代碼,直到我意識到錯在哪裏,因爲一切看起來都是正確的。事實上,它是。除了一件事情:您測試的結果是異步傳遞的,但您正在同步測試它。這意味着您需要將測試更改爲異步。

我假設你使用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); 
     } 
    }) 
}); 

對於一個承諾返回功能,這將是這樣的:

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

摩卡有一些承諾的糖,可以寫出最後一個功能(無功能包裝中的回調!):

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]} 
    }) 
}) 
+0

感謝您的時間!現貨在隊友。 – Kocur4d