Search code examples
javascriptreactjsunit-testingts-jest

How to mock a function using Jest that has parameters in it?


I have a method add which I want to mock:

A.js

function add(a, b, c) {
  return a + b + c
}

export add;

I am calling this add method in componentDidMount like this

B.js

import add from './A';

class AddForm extends React.Component {
    ...
    componentDidMount() {
       add(1, 2, 3);
    }
    ...
}

export AddForm;

Now this is how I am testing it

B.test.js

import AddForm from './B';

const helpers = require("./A");
jest.spyOn(helpers, "add").mockImplementation(() => 100);

describe('<AddForm/>', () => {
  test('should render all elements', () => {
     return render(
      <AddForm></AddForm>,
     );
  }
}

I am not getting the mocked value 100 while testing instead the function is getting executed. I tried all answers that are available but unable to get this mocked response.

Anything that I am missing here?


Solution

  • Check these documents

    Sample:

    const helpers = require("./A");
    jest.mock('./A')
    test('should render all elements', () => {
      helper.add.mockReturnValue(100);
      // write your test case
    });