【问题标题】:I am getting error on using toHaveBeenCalled() in jest?我在开玩笑中使用 toHaveBeenCalled() 时遇到错误?
【发布时间】:2021-03-01 11:22:17
【问题描述】:

我在使用 toHaveBeenCalled 时遇到错误,请纠正我哪里出错了

代码:

jsx

 <item
  onClick={ load ? undefined : onClick}
>

测试

test('render', () => {
const MockItems = jest.fn()
const prop = {
  onClick: MockItems,
}
const onclickProp=  output.find(item).props().onClick
onclickProp(undefined)

expect(props.onClick).toHaveBeenCalled()//error

}

错误

 expect(props.onClick).toHaveBeenCalled()

 Warning: An update to null inside a test was not wrapped in act(...).

When testing, code that causes React state updates should be wrapped into act(...):

act(() => {
  /* fire events that update state */
});
/* assert on the output */

【问题讨论】:

  • 你得到错误的原因是因为你试图改变反应调用堆栈之外的状态

标签: reactjs jestjs enzyme react-testing-library


【解决方案1】:

如果该项目作为子组件位于任何其他组件内,则需要在包装器组件上进行潜水()。浅渲染使您只能访问外部/父组件布局。

describe('item parent Component', () => {
  let wrapper,instance
  
  beforeEach(() => {
    mockProps = {
      handleClick: jest.fn()
    }
    const component = (<parent {...mockProps} />)
    wrapper = shallow(component).dive()
  })
  
  it('item is clicked', () => {
    wrapper.find(item).simulate('click')
    expect(handleClick).toHaveBeenCalled()
  })
)}
&lt;item onClick={ load ? undefined : onClick} &gt;

【讨论】:

  • handelCLick 和 mockProps 不可用
  • 你一定错过了什么。这显然是在同一个应付。能否附上完整的js和spec文件?
  • 你一定错过了什么。显然属于同一范围。能否附上完整的js和spec文件?
猜你喜欢
  • 2020-04-26
  • 2021-08-18
  • 1970-01-01
  • 1970-01-01
  • 2019-05-01
  • 2018-12-07
  • 1970-01-01
  • 2023-02-23
  • 1970-01-01
相关资源
最近更新 更多