javascript - 当 React 组件具有事件处理程序时,如何通过使用 enzyme shallow with contains 的测试用例

标签 javascript reactjs jestjs enzyme

当 react 组件具有事件处理程序时,我无法通过使用 .contain 的测试。示例:

Foo.js


 const Foo = React.createClass({
      render () {
        return (
          <p onClick={() => {}}>I am not a very smart component...</p>
        )
      }
    })
 export default Foo

Foo.test.js

import React from 'react'
import { shallow } from 'enzyme'

import Foo from './Foo'

describe('<Foo />', () => {
  it('renders a <p> with a static text', () => {
    const wrapper = shallow(<Foo />)
    console.log(wrapper.debug())
    expect(wrapper.contains(<p>I am not a very smart component...</p>)).toBe(true)
  })

使用 .debug() 时的控制台结果是

<p onClick={[Function]}>
    I am not a very smart component...
</p>

请注意onClick={[Function]}

我试图将我的测试用例更改为:

describe('<Foo />', () => {
  it('renders a <p> with a static text', () => {
    const wrapper = shallow(<Foo />)
    console.log(wrapper.debug())
    expect(wrapper.contains(<p onClick={() => {}}>I am not a very smart component...</p>)).toBe(true)
  })
})

但是测试还是没有通过。

我想知道:

  • 如何使用 shallow.contain 修复它并使测试通过,并简要解释为什么我当前的方法不起作用。

最佳答案

检查组件实例的属性及其值。 没有点击处理程序的实例与有点击处理程序的实例不同。

.contains(nodeOrNodes) => Boolean

Returns whether or not all given react elements match elements in the render tree. It will determine if an element in the wrapper matches the expected element by checking if the expected element has the same props as the wrapper's element and share the same values.

具有不同处理程序的实例也是不同的。

我们可以将点击处理程序作为 prop 传递给 Foo 组件。

import React from 'react'


class Foo extends React.Component {
  render() {
    return (
      <p onClick={this.props.onClick}>I am not a very smart component...</p>
    )
  }
}

export default Foo

通过将处理程序作为 props 传递,您可以注入(inject)模拟函数。

这样您就可以确定作为点击处理程序传递下来的 prop 值是模拟函数。

describe('<Foo />', () => {

  it('renders a <p> with a static text', () => {
    const fn = () => {};
    const wrapper = shallow(<Foo onClick={fn} />);

    expect(wrapper.contains(
        <p onClick={fn}>I am not a very smart component...</p>
    )).to.be(true);

  });

});

关于javascript - 当 React 组件具有事件处理程序时,如何通过使用 enzyme shallow with contains 的测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46139891/

相关文章:

javascript - 测试一个简单的组件在使用 JEST 被 withFormik() 包装时呈现

javascript - 将 Angular Directive(指令)应用于一组元素

javascript - 如何编写 JavaScript 测试用例

javascript - 强制一个 javascript 函数等待运行,直到第一个函数完成

javascript - 在reactjs中通过不同的id从api获取数据

node.js - MongoDB-Memory-Server 使 jest 测试调试卡在 WSL 上

javascript - 使用 'then' 方法在解析 promise 中强制执行顺序行为

javascript - React Native 有全局作用域吗?如果不是,我该如何模仿呢?

reactjs - React Modal 未正确显示

reactjs - 如何使用Width HOC模拟Material-UI