2017-06-05 7 views
0

フェッチを使用しているスタブ/テスト機能に問題があります。私はエラーを取得していますスタブフェッチのapiリクエスト

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返す約束、代わりの結果のように見える

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, 
     } 
    }) 
} 

そして、私のテスト:簡単な例を使用して

両方ともthenブロックを呼び出します。

テストをパスするにはどうすればよいですか?

答えて

3

すべてが間違っているとわかるまで、コードで遊ぶのに時間がかかりました。そして、実際それはそうでした。 1つのことを除いて:テストしている結果は非同期に配信されますが、同時に同期テストを行っています。つまり、テストを非同期に変更する必要があります。

私はあなたのテストランナーとしてMochaを使用していると仮定しており、非同期コードをテストする2つの方法があります。任意の非同期コードに対する標準的な方法の1つと、Promisesの特別な処理方法です。自分のスタイルに合ったものを使うことができます。

あなたが結果を後で配信されるすべての非同期コードをお持ちの場合、これは一般式である:約束を返す関数の場合

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

関連する問題