简体   繁体   English

如何在Jest测试中模拟React组件正在使用的功能?

[英]How do I mock a function being used by my React Component in Jest testing?

So I have something like the following: 所以我有以下内容:

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

class MyComponent extends React.Component {

   ...

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

My question is, when doing jest unit testing, I want to be able to mock the function calculate(). 我的问题是,在进行开玩笑的单元测试时,我希望能够模拟功能calculate()。 But the function is global to that file, and is not part of my react component. 但是该函数对该文件是全局的,并且不是我的react组件的一部分。 Is there a way to mock this function so it always returns say 1? 有没有办法模拟此函数,使其始终返回1? Thanks 谢谢

If you want to do this without any extra dependencies (like a mocking library), you should be able to use dependency injection by telling MyComponent which function to use by setting it in a prop on your component to achieve this, like so: 如果您想在没有任何额外依赖项的情况下执行此操作(例如模拟库),则应该能够通过在组件上的prop中将其设置为实现来告诉MyComponent使用哪个函数来使用依赖项注入,如下所示:

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

...and then, in your test, you can use a mock-calculate function: ...然后在测试中,您可以使用模拟计算功能:

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

If you want to use an actual mocking library instead, maybe try sinon.js Mocks . 如果您想使用实际的模拟库,则可以尝试sinon.js Mocks

You need a way to access the calculate function from outside of the file. 您需要一种从文件外部访问calculate函数的方法。 The easiest way to do this would be to export the function separately: 最简单的方法是分别导出函数:

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

This option is also minimally invasive to your source code. 此选项对您的源代码也具有最小的影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM