Jest没有认识到间谍被称为

时间:2018-04-02 22:39:10

标签: javascript reactjs unit-testing jestjs enzyme

我在确认使用Jest调用我的函数时遇到了一些麻烦。我有两个模拟功能。一个是嘲笑返回一个承诺,另一个是一个应该在第一个then()块中调用的简单间谍。

下面,在测试中,您将看到两个期望。第一个期望过去了。第二个没有。即expect(sendSpy).toHaveBeenCalled()通过但expect(sendCallbackSpy).toHaveBeenCalled()没通过。

然而,当我将console.log语句放在文件中时(如下所示),都执行(即'之前'和'之后'),如果我控制台登录window.props.onSend它确认模拟函数存在。所以看起来应该调用该函数。

另一点需要注意的是,我的实现要求我从props传入window对象中的回调。此外,要在Jest中window上模拟事物,你只需要模仿global,就像我在下面做的那样。我不认为这与这个问题有关,但值得指出。

是否可以在then()块中调用实际函数之前运行期望?

export class MyButton extends Component {
  handleClick = () => {
    this.props.send(this.props.url).then(res => {
      console.log('before', window.props.onSend)
      window.props.onSend(res.data)
      console.log('after')
    })
  }

  render() {
     return <button onClick={handleClick} />
  }
}



//test

  test('it calls the identity function when button is clicked', () => {
    const sendSpy = jest.fn(() => { return Promise.resolve({ data: 'hello' }) })
    const sendCallbackSpy = jest.fn()
    global.props = { onSend: sendCallbackSpy }

    wrapper = shallow(<MyButton send={sendSpy} } />)
    const button = wrapper.find('button')
    button.simulate('click')

    expect(sendSpy).toHaveBeenCalled()
    expect(sendCallbackSpy).toHaveBeenCalled()
  })

1 个答案:

答案 0 :(得分:1)

在测试第二个间谍之前,你需要等待承诺:

test('it calls the identity function when button is clicked', async() => {
    const request = Promise.resolve({ data: 'hello' })
    const sendSpy = jest.fn(() => request)
    const sendCallbackSpy = jest.fn()
    global.props = { onSend: sendCallbackSpy }

    wrapper = shallow(<MyButton send={sendSpy} } />)
    const button = wrapper.find('button')
    button.simulate('click')

    expect(sendSpy).toHaveBeenCalled()
    await request
    expect(sendCallbackSpy).toHaveBeenCalled()
})
相关问题