【问题标题】:Enzyme Shallow rendered instance does not inherit propsEnzyme Shallow 渲染实例不继承 props
【发布时间】:2018-04-23 16:10:31
【问题描述】:

假设我有一个这样的组件:

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})

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

【问题讨论】:

    标签: reactjs testing jestjs enzyme


    【解决方案1】:

    没必要,你能在创建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,因为我不使用 jest 但应该没有区别。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 2023-03-24
      • 2012-11-05
      相关资源
      最近更新 更多