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

查看:83
本文介绍了如何使用玩笑和酶来监视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调用,运行基于prop或其他任何功能的函数,那么这就是您应该测试的内容.模拟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天全站免登陆