2017-03-02 7 views
2

다음 작업을 통해 알림을 표시하고 제거한 다음 단위 테스트를 작성하려고합니다. setTimeout을 모의하는 방법을 알아 내라. 비동기 테스트에 REDUX 웹 사이트의 튜토리얼에 따라setTimeout을 사용하여 다른 작업을 호출하는 비동기 작업 작성자를 테스트하려면 어떻게합니까?

export const addNotification = (text, notificationType = 'success', time = 4000) => { 
     return (dispatch, getState) =>{ 
      let newId = new Date().getTime(); 
      dispatch({ 
       type: 'ADD_NOTIFICATION', 
       notificationType, 
       text, 
       id: newId 
      }); 
      setTimeout(()=>{ 
       dispatch(removeNotification(newId)) 
      }, time) 
     } 
    }; 
    export const removeNotification = (id) => (
    { 
     type: 'REMOVE_NOTIFICATION', 
     id 
    }); 

나는 다음과 같은 테스트를 내놓았다 :

import * as actions from '../../client/actions/notifyActionCreator' 
    import configureMockStore from 'redux-mock-store' 
    import thunk from 'redux-thunk' 

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


    describe('actions',()=>{ 

     it('should create an action to add a notification and then remove it',()=>{ 

      const store = mockStore({ notifications:[] }); 

      const text = 'test action'; 
      const notificationType = 'success'; 
      const time = 4000; 
      const newId = new Date().getTime(); 

      const expectedActions = [{ 
       type: 'ADD_NOTIFICATION', 
       notificationType, 
       text, 
       id: newId 
      },{ 
       type: 'REMOVE_NOTIFICATION', 
       id: newId 
      }]; 

      return store.dispatch(actions.addNotification(text,notificationType,time)) 
       .then(() => { 
        expect(store.getActions()).toEqual(expectedActions) 
       }); 
     }); 
    }); 

지금은 그냥 가게에서 정의되지 않은의 '다음'속성을 읽을 수 없습니다 오류가 발생합니다. 파견, 어떤 도움을 크게 주시면 감사하겠습니다.

+0

농담을하고 있습니까? –

답변

2

먼저 작업 작성자가 아무 것도 반환하지 않기 때문에 store.dispatch(actions.addNotification())으로 전화하면 undefined이 반환되므로 Cannot read property 'then' of undefined 오류가 발생합니다. .then()을 사용하려면 약속을 반환해야합니다.

따라서 작업 작성자 또는 테스트를 수정하여 작업 작성자가 실제로 수행 한 작업을 반영해야합니다. 테스트 통과하려면, 당신은 이런 식으로 테스트를 변경할 수 있습니다

// set up jest's fake timers so you don't actually have to wait 4s 
jest.useFakeTimers(); 

store.dispatch(actions.addNotification(text,notificationType,time)); 
jest.runAllTimers(); 
expect(store.getActions()).toEqual(expectedActions); 

또 다른 옵션은 in the Jest docs 세부 전략을 사용하는 것입니다. 이 전략을 사용하는 경우, 농담이 done()을 기다리는

// receive a function as argument 
test('should create an action to add a notification and then remove it', (done)=>{ 

    // ... 

    store.dispatch(actions.addNotification(text,notificationType,time)); 
    setTimeout(() => { 
     expect(store.getActions()).toEqual(expectedActions); 
     done(); 
    }, time); 
}); 

은 그렇지 않으면 시험 기관의 실행을 종료 할 때 종료 테스트를 고려할 것이라고합니다.

+0

감사합니다, 저를 위해 잘 작동합니다! –