2017-01-04 2 views
0

나는 다음과 같은 구성 요소가 있습니다componentDidMount 내부에서 setTimeout을 테스트 해 보시겠습니까?

class PlayButton extends Component { 
    constructor() { 
     super(); 

     this.state = { glow: false }; 
     this.play = this.play.bind(this); 
    } 
componentDidUpdate() { 
     if (this.props.media.currentTime === 0 && this.props.media.duration !== 0 && !this.state.glow) { 
      console.log('entering') 
      setTimeout(() => { 
       console.log('did time out') 
       this.setState({ glow: true }); 
      }, 3000); 
     } 

     if (this.props.media.currentTime !== 0 && this.state.glow) { 
      this.setState({ glow: false }); 
     } 
    } 

을 그리고 나는 componentDidMount 내부 setState를 검사 할 만 끝낼 수 없습니다

it('button shoould start glowing',() => { 
     const wrapper = mount(<PlayButton media={{ currentTime: 0, duration: 1 }}/>); 
     wrapper.update() 
     jest.runAllTimers(); 
     expect(wrapper.state('glow')).toBe(true); 
    }); 

어떤 생각? 감사합니다.

답변

0

당신은 대신 즉시 콜백을 호출 setTimeout의 모의에 전달할 수는 :

static defaultProps = { 
    timeout: setTimeout 
} 

this.props.timeout(() => { 
    console.log('did time out') 
    this.setState({ glow: true }); 
}, 3000); 

it('button shoould start glowing',() => { 
    const wrapper = mount(<PlayButton media={{ currentTime: 0, duration: 1 }} 
           timeout={(fn, _) => fn()}}/>); 
    wrapper.update() 
    jest.runAllTimers(); 
    expect(wrapper.state('glow')).toBe(true); 
}); 
+0

하지만 구성 요소를 변경해야합니다. 또한 상태가 변경된 경우에만 테스트를 수행하지 않으며 함수가 실행되었음을 나타냅니다. – Nicolas

1

알려줘야, 이것은 내가 그것을 해결하는 방법입니다

it('button shoould start glowing',() => { 
     let clock = sinon.useFakeTimers(); 
     const wrapper = mount(<PlayButton media={{ currentTime: 0, duration: 1 }}/>); 
     wrapper.update() 
     clock.tick(3000) 
     expect(wrapper.state('glow')).toBe(true); 
    });