Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to mock local functions using Jest

I have a file (file.js) consisting of 3 functions in the same file:

file.js:

const fn1 = (number) => {
    return number + 1;
}

export const fn2 = (value) => {
    return value;
}

export const fn3 = (number) => {
    return fn1(number);
}

export const fn4 = (number) => {
    return fn2(number);
}

Is it possible to mock out these functions periodically using JEST? What I hope to achieve is something along these lines:

file.test.js:

import { fn2, fn3, fn4 } from 'file.js';

describe('fn2', () => {
  test('normal test.' => {
    expect(fn2(1)).toBe(1);
  })
});

describe('fn3', () => {
  test('mock fn1 for this test.' => {
    mock fn1 = () => { return 1 };

    expect(fn3(2)).toBe(1);
  })
});

describe('fn4', () => {
  test('mock fn2 for this test.' => {
    mock fn2 = () => { return 1 };

    expect(fn4(2)).toBe(1);
  })
});
like image 678
dropbeardan Avatar asked Feb 22 '18 05:02

dropbeardan


1 Answers

It is not possible through the way how JS modules work. Only exported functions are visible to the outside, all other stuff is only visible in the scope of the module, so there is no way to mock it. Also there is no need to mock this function as you only want to test the public API.

The only way to test the function itself and mock it for this module is to put it into an own module, which makes sense if it is some really complicated function where you need good test coverage and it is to complicated to get this when its in another module.

like image 127
Andreas Köberle Avatar answered Nov 04 '22 03:11

Andreas Köberle