繁体   English   中英

开玩笑如何测试调用 function 的线路?

[英]Jest how to test the line which calls a function?

我有一个命令行应用程序。 该文件有几个功能,但我如何测试调用第一个 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() function并检查它是否在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()保存在同一个文件中的同时,我不知道有什么方法可以做同样的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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