如何使用笑话和酶来监视 componentWillMount [英] How to spy componentWillMount using jest and enzyme

查看:20
本文介绍了如何使用笑话和酶来监视 componentWillMount的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试是否调用了 componentWillMount,为此我的测试是

I am trying to test whether componentWillMount was called and for that my test is

test('calls `componentWillMount` before rendering', () => {
  let fn = jest.fn(SomeComponent.prototype.componentWillMount)
  mount(<SomeComponent />)
  expect(fn).toHaveBeenCalled()
})

但是即使调用了componentWillMount方法,测试也没有通过.我在这里错过了什么?

But even though the componentWillMount method is called, the test does not pass. What am I missing here?

推荐答案

我不知道其他答案是否对您的问题有所帮助,但您不需要测试 componentWillMount.React 应该已经为你做了那个测试.

I don't know if the other answers have helped with your question, but you shouldn't need to test componentWillMount. React should already do that testing for you.

与您的测试更相关的是测试您在该方法中为组件放置的功能或操作.

More relevant to your testing would be to test the functions or actions you are putting in that method for your component.

如果您要进行一些 API 调用、运行基于 props 的函数或其他任何东西,这就是您应该测试的内容.模拟 componentWillMount 触发的函数/动作/代码,并对其进行断言和期望.

If you are making some API call, running a function based on props, or anything else, that is what you should be testing for. Mock the function/action/code that componentWillMount triggers, and make assertions and expectations on that.

示例:

组件:

class YourComponent extends Component {

  componentWillMount() {
    /*this fetch function is actually what you want to test*/
    this.props.fetch('data')
  }

  render() {
    /* whatever your component renders*/ 
  }    
}

测试:

test('should call fetch when mounted', () => {
  let mockFetch = jest.fn()

  const wrapper = mount(<SomeComponent fetch={mockFetch}/>);

  expect(wrapper).toBeDefined();
  expect(mockFetch).toHaveBeenCalled();
  expect(mockFetch.mock.calls[0]).toEqual(['data'])
});

这篇关于如何使用笑话和酶来监视 componentWillMount的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆