简体   繁体   中英

Jest how to test the line which calls a function?

I have a command line application. The file has several functions but how can I test the line that calls the first function.

For example

function child(ch) {
  console.log(ch);
}


function main(a) {
  console.log(a);
  child('1');
}

main(24);

How can I test here that main has been called when the file loads.

If you don't mind splitting your file in two different files:

index.js

import main from './main.js';

main(24);

main.js

function child(ch) {
  console.log(ch);
}


function main(a) {
  console.log(a);
  child('1');
}

export default main;

You can then mock the main() function from main.js and check that it gets called on index.js import:

index.spec.js

const mockedMain = jest.fn();

jest.mock('../main.js', () => ({
  default: () => mockedMain(),
}));

describe('test that main is called on index.js import', () => {
  it('should call main', () => {
    require('../index.js');
    expect(mockedMain).toHaveBeenCalled();
  });
});

I do not know any way to do the same thing while keeping main() in the same file.

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