简体   繁体   English

使用 jest/enzyme 在 React 上测试 ComponentDidMount 失败

[英]Test Failing in ComponentDidMount on React using jest/enzyme

Home.js主页.js


class Home extends Component {

  componentDidMount() {
    console.log("Check")
  }

  render() {
    return (
      <div>Home Page Screen</div>
    )
  }
}

export default Home

Home.test.js主页.test.js

import React from "react"
import Enzyme, { mount } from "enzyme"
import EnzymeAdapter from "enzyme-adapter-react-16"
import Home from "./Home"

Enzyme.configure({ adapter: new EnzymeAdapter() })

test("componet Lifecycle test", () => {
  const wrapper = mount(<Home />)
  const spy = jest.spyOn(wrapper.instance(), "componentDidMount")
  expect(spy).toHaveBeenCalledTimes(1)
}) 

output of Test Case测试用例 output

src/Home.test.js
  ● Console

    console.log src/Home.js:6
      Check

  ● componet Lifecycle test

    expect(jest.fn()).toHaveBeenCalledTimes(expected)

    Expected number of calls: 1
    Received number of calls: 0

      15 |   const wrapper = mount(<Home />)
      16 |   const spy = jest.spyOn(wrapper.instance(), "componentDidMount")
    > 17 |   expect(spy).toHaveBeenCalledTimes(1)
         |               ^
      18 | }) 

      at Object.<anonymous> (src/Home.test.js:17:15)

when I tried to check whether the componentDidMount Life cycle method is calling in the component Home using jest/enzyme is failing but in the browser, the component lifecycle method is calling fine当我尝试检查是否使用 jest/enzyme 在组件主页中调用 componentDidMount 生命周期方法失败但在浏览器中,组件生命周期方法调用正常

I don't think it's too important that you check if componentDidMount itself is called but you can assert other stuff has happened by triggering it.我认为检查是否调用了componentDidMount本身并不重要,但您可以通过触发它来断言其他事情已经发生。 there isn't much value in just asserting that it was called仅仅断言它被调用并没有多大价值

for example if you're component sets some state on mount then you can write a test like this:例如,如果您的组件在安装时设置了一些 state,那么您可以编写如下测试:

componentDidMount() {
    this.setState({something: 'hello'})
}
wrapper.setState({ something: '' })
wrapper.instance().componentDidMount()
expect(wrapper.state('something')).toEqual('hello')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM