Jest 如何测试调用函数的行?

Jest how to test the line which calls a function?

我有一个命令行应用程序。 该文件有几个函数,但我如何测试调用第一个函数的行。

例如

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


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

main(24);

我如何在这里测试加载文件时是否调用了 main。

如果您不介意将文件拆分为两个不同的文件:

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;

然后您可以从 main.js 模拟 main() 函数并检查它是否在 index.js 导入:

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

我不知道有什么方法可以在将 main() 保存在同一个文件中的同时做同样的事情。