2017-02-28 5 views
0

내가 다음 래퍼 구성 요소가 말 .시험 비동기 중첩 된 구성 요소

이제 다음과 같이 나는 액션이 ​​기록 구독하기 말할 수 있습니다 :

Unhandled rejection Error: Error: connect ECONNREFUSED 127.0.0.1:8080 
:이 결과

/* global window, test, expect, beforeAll, afterAll, describe */ 

'use strict' 

import React from 'react' 
import FooDisplay from './index' 
import {mount} from 'enzyme' 
import {Provider} from 'react-redux' 
import configureStore from '../../store/configureStore' 
import nock, {uriString} from '../../config/nock' 
import _ from 'lodash' 


const env = _.cloneDeep(process.env) 
describe('the component behaves correctly when integrating with store and reducers/http',() => { 
    beforeAll(() => { 
    nock.disableNetConnect() 
    process.env.API_URL = uriString 
    }) 

    afterAll(() => { 
    process.env = _.cloneDeep(env) 
    nock.enableNetConnect() 
    nock.cleanAll() 
    }) 

    test('when deep rendering, the load event populates the input correctly',() => { 
    const store = configureStore({ 
     address: { 
     address: 'foo' 
     } 
    }) 
    const display = mount(<Provider store={store}><FooDisplay /></Provider>, 
     {attachTo: document.getElementById('root')}) 
    expect(display.find('p').find('.address').text()).toEqual('foo') 
    const button = display.find('LoadFromServerButton') 
    expect(button.text()).toEqual('fetch serverside address') 
    nock.get('/dummy_address').reply(200, {address: 'new address'}) 
    button.simulate('click') 
    }) 
}) 

:

export const get =() => dispatch => http('/dummy_route') 
     .spread((response, body) => dispatch(actOnThing(update, body))) 

을 지금은 시험과 같이 작성하는 경우

조금 생각한 후에, 이것은 버튼 클릭으로 인해 테스트가 약속을 반환하지 않는다는 사실 때문입니다 e는 후드 아래에서 발사 할 것을 약속하므로 afterAll이 즉시 실행되고 노크가 제거되며 실제 http 연결이 전선을 통해 진행됩니다.

이 케이스는 어떻게 테스트합니까? 올바른 약속을 쉽게 반환 할 수있는 방법이없는 것 같습니다.이 업데이트로 인해 DOM에 대한 업데이트를 테스트하려면 어떻게해야합니까?

+0

당신이 거부 된 약속을 처리하지 않은 것처럼 보입니다. 오프라인 환경을 시뮬레이션하려고 했습니까? nock.disableNetConnect()와 그 상대방을 제거하면 어떻게됩니까? 테스트에서 비동기 작업을 수행하는 경우 done 매개 변수를 포함하고 비동기 작업이 완료되면이를 호출해야합니다. 대안으로 시험에 대한 약속을 되돌릴 수도 있습니다. https://facebook.github.io/jest/docs/asynchronous.html – nbkhope

+0

예 아니요, 이해합니다.하지만 어떻게 올바른 약속을 되돌릴 수 있습니까? 버튼을 클릭하면 비동기 작업이 트리거되고 테스트에서 올바른 테스트가 반환되도록하는 방법이 명확하지 않습니다. –

+0

"업데이트"기능의 정의는 어디에 있습니까? 나는 this.props.getFoo()와 같은 느낌이 LoadFromServerButton의 doUpdate 함수 안에 this.props.get()이 될거야? – nbkhope

답변

0

문제는 테스트에서 돌아 오지 않을 것이라는 점입니다. 그래서 get 반환 A는 그냥 직접 장전을 사용하지 않고 get을 조롱 할 수 있습니다 약속을 알고 있어야합니다 : 당신이 다음 약속을 만들 수 있습니다

import {get} from '../../actions/actions' 
jest.mock('../../actions/actions',() => ({get: jest.fn})) 

이 객체와 테스트에 {get: jestSpy}

를 동작 모듈을 교체하고하자 get 이것을 반환하고 시험에서이 약속을 되 찾을 수 있습니다.

it('',()=>{ 
    const p = new Promise.resolve('success') 
    get.mockImplementation(() => p)//let get return the resolved promise 
    //test you suff 
    return p 
})