简体   繁体   中英

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);
  })
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM