2

I want to test calculate() in jest and I don't want to call actual implementation of add() and subtract(). How can I mock these implementations? This is just a sample code which I'm not sure is functional but what I want to ask is that how do I mock the nested functions add() and subtract() while testing calculate() so that when I test calculate() I don't call the actual implementations of add and subtract?

calculator.js

function add(){
    return 1+1;
}

function subtract(){
    return 2-1;
}

function calculate(){
    add();
    subtract();
}

module.exports = { add, subtract, calculate}

EDIT: Yes all these functions are in the same module.

calculator-test.js

describe('calculator.js', () => {
    it('Testing calculate() without calling add and subtract ', () => {
    const helper = require('calculator');

    helper.add = jest.fn();
    helper.subtract = jest.fn();

    helper.calculate();

    // I don't know....How do I test calculate() ??
})

EDIT2: This is NOT a duplicate question that has been tagged. I have already stated I am facing problems with functions in the same module not in different modules which is answered and you are tagging it as a duplicate.

Sarmad
  • 303
  • 3
  • 16
  • 1
    Assuming add and subtract are available via export or any other mechanism to your test files, you can do `spyOn('add').and.returnValue(desired_val)` – Rikin Jul 09 '18 at 14:10
  • Just define them as `jest.fn()` and test if they've been called https://jest-bot.github.io/jest/docs/expect.html#tohavebeencalled – t3__rry Jul 09 '18 at 15:41
  • @t3__rry I have tried doing jest.fn() but what if I want to return some value from it? – Sarmad Jul 09 '18 at 16:01

0 Answers0