thatDubstepSound
thatDubstepSound

Reputation: 357

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(). But the function is global to that file, and is not part of my react component. Is there a way to mock this function so it always returns say 1? Thanks

Upvotes: 0

Views: 197

Answers (2)

Frost
Frost

Reputation: 11977

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:

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.

Upvotes: 1

djfdev
djfdev

Reputation: 6037

You need a way to access the calculate function from outside of the file. 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.

Upvotes: 0

Related Questions