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

时间:2021-01-19 10:44:29

标签: javascript node.js jestjs testng

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

例如

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


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

main(24);

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

1 个答案:

答案 0 :(得分:1)

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

index.js

import main from './main.js';

main(24);

ma​​in.js

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


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

export default main;

然后您可以模拟 main.js 中的 main() 函数并检查它是否在 index.js 导入时被调用:< /p>

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() 保存在同一个文件中的同时,我不知道有什么方法可以做同样的事情。