【问题标题】:How do I mock a function being used by my React Component in Jest testing?如何在 Jest 测试中模拟我的 React 组件使用的函数?
【发布时间】:2018-12-03 20:58:19
【问题描述】:

所以我有如下内容:

function calculate = (value) => { return value + somecalculations }

class MyComponent extends React.Component {

   ...

   render() {
       if (calcuate(this.props.value) === 1) {
          return(<MyComponentVersion1 />)
       } else {
          return <MyComponentVersion2 />
       }
   }
}

我的问题是,在进行开玩笑的单元测试时,我希望能够模拟函数 calculate()。但是该函数对该文件是全局的,并且不是我的反应组件的一部分。有没有办法模拟这个函数,所以它总是返回 1?谢谢

【问题讨论】:

  • 它没有以任何其他方式导出或暴露?我的意思是,测试内部功能的目的是什么?现在编写代码的方式需要更改value。如果您需要模拟calculate,那么听起来它应该可以自行测试,因此导出或在单独的模块中,那么这个问题就消失了。 (是的,像重新布线这样的工作,但它几乎总是替代适当的设计,IMO。)
  • 您正在控制传递给calculate 的值,因此通过将某些值传递给您的组件,您将期望它以可预测的方式运行。测试这些场景不要打扰测试计算本身。

标签: reactjs jestjs


【解决方案1】:

如果您想在没有任何额外依赖项的情况下执行此操作(如模拟库),您应该能够通过告诉MyComponent 使用哪个函数来使用依赖注入,方法是将其设置在组件的 prop 中以实现此目的,像这样:

calculate = (value) => { return value + somecalculations }

class MyComponent extends React.Component {
    constructor(props) {
        this.calculate = this.props.calculate || calculate
    }

    render() {
        if (this.calculate(this.props.value) === 1 {
            return (<MyComponentVersion1 />)
        } else {
            return (<MyComponentVersion2 />)
        }
    }
}

...然后,在您的测试中,您可以使用模拟计算函数:

test('put a really good test description here', () => {
    const mockCalculate = () => 1
    const myTestSubject = (<MyComponent calculate={mockCalculate} value={whatever}/>)
    // the rest of your test
})

如果您想改用实际的模拟库,不妨试试sinon.js Mocks

【讨论】:

    【解决方案2】:

    您需要一种从文件外部访问calculate 函数的方法。最简单的方法是单独导出函数:

    export function calculate () {
      // ...
    }
    

    此选项对您的源代码的侵入性也很小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-10
      • 2018-01-26
      • 1970-01-01
      • 2019-09-03
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多