Fauzi Alhari
Fauzi Alhari

Reputation: 11

How to test if a function inside function called with right parameter

I got this kind of function:

const plus1 = x => x + 1;

const plus2 = x => x + 2;

const returnPlus1OrPlus2 = (number, code) =>
  code === 1 ? plus1(number * 3) : plus2(number);
// if the parameter code is 1 then call function plus1 with param number*3,
// if not then just call function plus2 with param number

export default returnPlus1orPlus2;  

I have to create a unit testing using jest for that function and I need to test if the function returnPlus1OrPlus2 calls the right function whether plus1 or plus2 based on the parameter code invoked.

    test('function returnPlus1OrPlus2 should call function plus1'()=>{
        expect(returnPlus1OrPlus2(2, 1)).toBe(7);
        //expect(function plus 1 was called with 6)
    })

How to mock functions plus1 and plus2 and write something like this in test?

//expect(function plus1 was called with 6)

Upvotes: 1

Views: 135

Answers (1)

Lin Du
Lin Du

Reputation: 102307

If you want to mock or spy on the function(plus1, plus2), you need to make sure you can access it. Then, use jest.spyOn add a spy on the function and assert it is to be called or not. Here is the solution:

index.js:

const plus1 = x => x + 1;

const plus2 = x => x + 2;

const returnPlus1OrPlus2 = (number, code) =>
  code === 1 ? exports.plus1(number * 3) : exports.plus2(number);

exports.plus1 = plus1;
exports.plus2 = plus2;
export default returnPlus1OrPlus2;

index.spec.js:

import returnPlus1orPlus2 from "./";
const mymath = require("./");

describe("returnPlus1orPlus2", () => {
  it("should call plus1", () => {
    const plus1Spy = jest.spyOn(mymath, "plus1");
    expect(returnPlus1orPlus2(2, 1)).toBe(7);
    expect(plus1Spy).toBeCalledWith(6);
  });

  it("should call plus2", () => {
    const plus2Spy = jest.spyOn(mymath, "plus2");
    expect(returnPlus1orPlus2(2, 2)).toBe(4);
    expect(plus2Spy).toBeCalledWith(2);
  });
});

Unit test result with 100% coverage:

 PASS  src/stackoverflow/59168766/index.spec.js
  returnPlus1orPlus2
    ✓ should call plus1 (5ms)
    ✓ should call plus2 (1ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.js |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        4.109s, estimated 8s

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59168766

Upvotes: 1

Related Questions