【问题标题】:Using Jest and Enzyme, how do I test a function passed in through props?使用 Jest 和 Enzyme,如何测试通过 props 传入的函数?
【发布时间】:2019-05-12 18:41:55
【问题描述】:

使用 Jest 和 Enzyme,如何测试 this.props.functionToTest 是否运行?

class TestComponent extends Component {
   static propTypes = {
     functionToTest: PropTypes.func
   }
   componentDidMount() {
     this.props.functionToTest()
   }
}

在 Jest 中,我尝试创建 mockProps 并在安装组件时将它们传入。

let props = {
  functionToTest = jest.fn(() => {});
}
beforeEach(() => {
  const wrapper = mount(<TestComponent {...props} />
}

componentDidMount 函数中的 console.log 将 functionToTest 显示为未定义。显然在 mount 时传入 props 是行不通的。

问题 1:如何传入将在 componentDidMount 函数中显示的模拟道具?

问题 2:一旦该函数可用,我如何获得对该函数的访问权限,以便我可以使用 spyOn 或类似的东西来测试该函数是否已运行?

【问题讨论】:

    标签: javascript reactjs jestjs enzyme


    【解决方案1】:

    我不知道您的确切设置,但我会这样做:

    • 像你一样用jest.fn()模拟函数
    • 将 mock 传递给正在挂载的组件(就像您所做的那样)
    • 检查是否使用expect(...).toBeCalled().toHaveBeenCalled() 运行(不同Jest 版本之间有所不同)

    .

    let props = {
      functionToTest: jest.fn() // You don't need to define the implementation if it's empty
    };
    
    beforeEach(() => {
      const wrapper = mount(<TestComponent {...props} />
    }
    
    // In the test code:
    it('does something', () => {
        expect(props.functionToTest).toBeCalled();
        // OR... depending on your version of Jest
        expect(props.functionToTest).toHaveBeenCalled();
    });
    

    【讨论】:

    • componentDidMount 中的 console.log 中的 props 仍将每个 prop 显示为未定义。我如何将 TestComponent 导入 Jest 测试与它有什么关系?我只是使用 import TestComponent from "../TestComponent" 导入它
    • 如果该组件没有模拟(可能在测试文件中或设置在附近的 __mocks__ 文件夹中),那么这仅取决于从组件导出的内容。如果您能够安装它,我不会猜测那里有问题,但也许值得尝试访问它上面的任何其他东西,以证明它是您获得的正确组件。
    • 我能想到的唯一可能影响这一点的事情是我正在使用 Redux。所以 TestComponent 的底部是 export default connect( mapStateToProps, mapDispatchToProps, }(TestComponent) 我认为这不会对此产生任何影响,因为 functionToTest 是通过父组件传入的,而不是 redux。
    • 这确实改变了一些事情。您的预期组件成为包装器中的子组件。我鼓励您分离组件并使用展开的版本而不是进行单元测试,因为它会让您的生活更轻松。但是,如果您想要或需要满足于可读性较差的代码,请从wrapper.childAt(0) 获取内部组件。但是,如果您需要在测试中对组件实例执行其他操作,您只需要经历这些麻烦。如果您只是想测试是否已调用functionToTest,那么上面的答案应该足够了,并且可以编写可读的代码。
    【解决方案2】:

    问题最终是 TestComponent 仅在 Redux 包装器中导出。在类级别添加导出并在 Jest 测试导入中对其进行解构,以及上面发布的解决方案 Henrick 修复它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-31
      • 1970-01-01
      • 2018-10-20
      • 2018-08-28
      • 2019-02-03
      • 2018-11-04
      • 2020-10-09
      相关资源
      最近更新 更多