2017-04-18 6 views
1

Thunk로 API에서 데이터를 가져 오기위한 간단한 액션을 만들고 있습니다. 그것은 다음과 같습니다Jest와 Sinon으로 Thunk 액션을 테스트하는 방법

import fetch from 'isomorphic-fetch'; 

function json(response) { 
    return response.json(); 
} 

/** 
* Fetches books from the server 
*/ 
export function getBooks() { 
    return function(dispatch) { 
    fetch("http://localhost:1357/book", {mode: "cors"}) 
    .then(json) 
    .then(function(data) { 
     dispatch({ 
     type: "GET_BOOKS", 
     devices: data 
     }); 
    }); 
    } 
}; 

그것은 한 번 fetch를 호출해야합니다. 웹 브라우저에서 호출 할 때 데이터를 성공적으로 가져 오기 때문에이 작업이 수행되는지 확인했습니다. 내가이 시험을 쓸 때, :

import fetch from 'isomorphic-fetch'; 
let spy = sinon.spy(fetch); 
import configureMockStore from 'redux-mock-store'; 
import thunk from 'redux-thunk'; 
import {getBooks} from '../../actions/getBooks'; 
import sinon from 'sinon'; 

const middlewares = [ thunk ]; 
const mockStore = configureMockStore(middlewares); 

describe('async actions',() => { 

    it('calls the server',() => { 
    const store = mockStore({books: []}); 
    store.dispatch(getBooks()); 
     expect(spy.callCount).toEqual(1); 
     spy.restore(); 
    }); 
}); 

그러나이 테스트가 실패하고 spy의 호출 수를 나는 이것이 왜 시험 전에 조치가 가져올 가져올 예정이다 의심 0입니다 스파이는 파일의 맨 위에 만들어집니다. 그러나 이것은 작동하지 않습니다. fetch이 호출되고 있는지 테스트하는 권장 방법은 무엇입니까?

답변

1

http://arnaudbenard.com/redux-mock-store/에서 읽기, 부분 비동기 동작.

나는 당신이 당신의 시험에서 약속을 사용하지 않기 때문에 일어난다 고 생각합니다.

it('calls the server', (done) => { 
    const store = mockStore({books: []}); 
    store.dispatch(getBooks()).then(() => { 
     expect(spy.callCount).toEqual(1); 
     spy.restore(); 
     done(); 
    }); 
    }); 
+0

도움 주셔서 감사합니다. 테스트를 실행하면 '속성을 읽을 수 없습니다', '정의되지 않았습니다.'라는 오류가 발생합니다. 나는 이것이 상점이 정의되지 않았다는 것을 의미한다고 가정하고 있지만 그것을 정의했다. 왜 이런 일이 일어나는 지 아십니까? – user2367593

+1

Nevermind - 코드를'fetch (localhost ...') 대신'return fetch (localhost ...')라고 바꾸어야했습니다. – user2367593