Enzyme Shallow渲染实例不继承道具

时间:2017-11-10 12:18:25

标签: reactjs testing jestjs enzyme

说我有这样的组件:

class ExampleComponent extends Component {
  exampleMethod = () => {
    this.props.examplePropFunction()
  }
}
然后我按照这样构建我的测试:

it('exampleMethod', () => {
  const examplePropMock = jest.fn()
  const wrapper = shallow(<ExampleComponent examplePropFunction={examplePropMock}/>)
  wrapper.instance().exampleMethod()
  expect(examplePropMock).toHaveBeenCalled()
})

失败
TypeError: _this.props.examplePropFunction is not a function

console.logging它显示它实际上是未定义的。

一个简单的解决方案是运行:

wrapper.setProps({examplePropFunction: examplePropMock})

在拍摄实例之前。我的问题是,为什么最后一步是必要的?

1 个答案:

答案 0 :(得分:0)

没有必要,你可以检查examplePropMock在创建它时是否真的是间谍功能而不是未定义,你是否安装了最新的软件包?你必须在某个地方做错事。我刚测试过它:

example.js

import { Component } from 'react';

class ExampleComponent extends Component {
  exampleMethod = () => {
    this.props.examplePropFunction()
  }
  render() {
    return null;
  }
}

export default ExampleComponent;

example.spec.js

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

import ExampleComponent from './example';

it('exampleMethod', () => {
  const examplePropMock = expect.createSpy();
  const wrapper = shallow(<ExampleComponent examplePropFunction={examplePropMock} />);

  wrapper.instance().exampleMethod();

  expect(examplePropMock).toHaveBeenCalled();
});

使用setProps或手动传递道具时可以使用。

使用这些包进行测试:

"react": "^15.6.0",
"enzyme": "^2.5.1",
"expect": "^1.20.2",

我使用expect assertions来创建间谍而不是开玩笑因为我不使用jest但是应该没有区别。