当 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/