2017-04-23 2 views
1

간단한 thunk 액션을 작성하여 API에서 데이터를 가져 왔습니다. 그것은 다음과 같습니다동형 피치가있는 Sinon 스파이

import configureMockStore from 'redux-mock-store'; 
import thunk from 'redux-thunk'; 
import {getBooks} from '../../actions/getBooks'; 
import nock from 'nock'; 
import fetch from 'isomorphic-fetch'; 
import sinon from 'sinon'; 

it('returns the found devices',() => { 
    var devices = nock("http://localhost:1357") 
       .get("/book") 
       .reply(200, 
         {}); 
    const store = mockStore({devices: []}); 
    var spy = sinon.spy(fetch); 
    return store.dispatch(getBooks()).then(() => { 
    }).catch((err) => { 
    }).then(() => { 
    // https://gist.github.com/jish/e9bcd75e391a2b21206b 
    expect(spy.callCount).toEqual(1); 
    spy.retore(); 
    }); 
}); 

이 테스트가 실패 - 호출 수가 0하지 1입니다 :

import fetch from 'isomorphic-fetch'; 

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

/** 
* Fetches booksfrom the server 
*/ 
export function getBooks() { 
    return function(dispatch) { 
    return fetch("http://localhost:1357/book", {mode: "cors"}) 
    .then(json) 
    .then(function(data) { 
     dispatch({ 
     type: "GET_Books", 
     books: data 
     }); 
     // This lets us use promises if we want 
     return(data); 
    }); 
    } 
}; 

그런 다음, 나는이 같은 테스트를 썼다. sinon이 기능을 조롱하지 않는 이유는 무엇입니까? 기능을 조롱하게하려면 어떻게해야합니까?

답변

2

테스트 파일에서 가져 오기를 가져오고 어디에서나 호출하지 않습니다. 그래서 호출 수가 0입니다.

이렇게하면 테스트 설명이 "발견 된 장치를 반환 할 때"작업 작성자가 처음 호출되는 이유는 무엇입니까?

썽크 액션 크리에이터의 주된 목적은 나중에 호출 할 수있는 함수를 반환하는 액션 크리에이터입니다. 나중에 호출되는이 함수는 점포 디스패치 및 상태를 인수로 수신 할 수 있습니다. 이렇게하면 반환 된 함수가 추가 작업을 비동기 적으로 디스패치 할 수 있습니다.

썽크 작업 작성자를 테스트 할 때는 다음과 같은 경우에 올바른 작업이 전달되는지 여부에 중점을 두어야합니다.

  1. 는 요청은

  2. 응답이 수신을 만들어

  3. 오류가 발생하고이

은 다음과 같은 것을 시도 실패 인출 인출이 성공한다 :

export function fetchBooksRequest() { 
    return { 
    type: 'FETCH_BOOKS_REQUEST' 
    } 
} 

export function fetchBooksSuccess (books) { 
    return { 
    type: 'FETCH_BOOKS_SUCCESS', 
    books: books 
    } 
} 

export function fetchBooksFailure (err) { 
    return { 
    type: 'FETCH_BOOKS_FAILURE', 
    err 
    } 
} 


/** 
* Fetches books from the server 
*/ 
export function getBooks() { 
    return function(dispatch) { 
    dispatch(fetchBooksRequest(data)); 

    return fetch("http://localhost:1357/book", {mode: "cors"}) 
    .then(json) 
    .then(function(data) { 
     dispatch(fetchBooksSuccess(data)); 
     // This lets us use promises if we want 
     return(data); 
    }).catch(function(err) { 
     dispatch(fetchBooksFailure(err)); 
    }) 
    } 
}; 

Tests.js

import configureMockStore from 'redux-mock-store' 
import thunk from 'redux-thunk' 
import fetchMock from 'fetch-mock' // You can use any http mocking library 

import {getBooks} from '../../actions/getBooks'; 

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

describe('Test thunk action creator',() => { 
    it('expected actions should be dispatched on successful request',() => { 
    const store = mockStore({}) 
    const expectedActions = [ 
     'FETCH_BOOKS_REQUEST', 
     'FETCH_BOOKS_SUCCESS' 
    ] 

// Mock the fetch() global to always return the same value for GET 
// requests to all URLs. 
fetchMock.get('*', { response: 200 }) 

    return store.dispatch(fetchBooks()) 
     .then(() => { 
     const actualActions = store.getActions().map(action => action.type) 
     expect(actualActions).toEqual(expectedActions) 
    }) 

    fetchMock.restore() 
    }) 

    it('expected actions should be dispatched on failed request',() => { 
    const store = mockStore({}) 
    const expectedActions = [ 
     'FETCH_BOOKS_REQUEST', 
     'FETCH_BOOKS_FAILURE' 
    ] 
// Mock the fetch() global to always return the same value for GET 
// requests to all URLs. 
fetchMock.get('*', { response: 404 }) 

    return store.dispatch(fetchBooks()) 
     .then(() => { 
     const actualActions = store.getActions().map(action => action.type) 
     expect(actualActions).toEqual(expectedActions) 
    }) 

    fetchMock.restore() 
    }) 
})