2016-10-07 7 views
0

私は反応/ reduxアプリケーションで次のapiミドルウェアを持っています。これはjestとunittestingしています。このapiミドルウェアがフェッチによってスローされたエラーを処理するかどうかをjestでどのようにテストしますか?

// ./src/middleware/api.js 

import fetch from 'isomorphic-fetch'; 

// Checks if the returned statuscode is in the successful range 
const handleErrors = (response) => { 
    if (!response.ok) { 
    throw Error(response.statusText); 
    } 
    return response; 
}; 

export const get = (endpoint) => { 
    const options = { credentials: 'include', method: 'GET' }; 

    return fetch(endpoint, options) 
    .then(handleErrors) 
    .then(response => response.json()) 
    .catch(error => error.message); 
}; 

とテストは次のとおりです:モジュールのコードがあり、私はそれが(例えばネットワーク接続がないときに)フェッチによってスローされたエラーをキャッチするかどうかをテストしたい最後のアサーションで

// ./src/middleware/__tests__/api.test.js 

import fetch from 'isomorphic-fetch'; 
import { get } from '../api'; 

// Mock calls to fetch by the api middleware 
// loads https://github.com/jefflau/jest-fetch-mock instead of fetch 
jest.mock('isomorphic-fetch'); 

describe('api middleware',() => { 
    describe('get',() => { 
    it('should return the response on success',() => { 
     const expected = { data: ['data'], meta: {} }; 
     const body = JSON.stringify(expected); 
     const init = { status: 200, statusText: 'OK' }; 

     fetch.mockResponseOnce(body, init); 

     return get('http://endpoint').then(actual => expect(actual).toEqual(expected)); 
    }); 

    it('should return the statusText for unsuccessful status codes',() => { 
     const expected = 'Unauthorized'; 
     const body = JSON.stringify({ errors: ['You are not logged in'] }); 
     const init = { status: 401, statusText: expected }; 

     fetch.mockResponseOnce(body, init); 

     return get('http://endpoint').then(actual => expect(actual).toEqual(expected)); 
    }); 

    // I have not been able to mock this so far  
    it('handles fetch errors',() => { 
     return get('doesnotexist').then(actual => expect(actual).toEqual(false)); 
    }); 
    }); 
}); 

。しかし、私はそれをテストすることに問題があります。フェッチでエラーをどのようにシミュレートしてからテストするのかは分かりません。私は最後の主張を嘲笑する方法を知っていますか?

答えて

3

jest-fetch-mockの実装を見ると、常に約束を解決します。つまり、fetchは決してcatchにはなりません。だから、Promise.reject()を持っている必要がありますし、あなたのテストであなたのような何か行う必要があります - あなたはそれを、それはあなたの約束のキャッチ部分をトリップする無効な体を与えた場合

it('handles fetch errors',() => { 
    return get('doesnotexist') 
    .catch(error => expect(error).toEqual('some error')); 
}); 
0

を。

fetch.mockResponseOnce(null, init); 
関連する問題