我知道达到 100% 的单元测试覆盖率不应该是一个目标。我实际上已经从覆盖测试中排除了 index.js
,我只是想知道它是如何完成的。
如何测试index.js
中的自执行功能?我想测试它调用 scrape
。
index.js
:
import scrape from './scrape';
const main = (async () => {
await scrape();
})();
export default main;
我尝试过的:
import main from './index';
const scrape = jest.fn();
describe('On the index file', () => {
it('scrape executes automatically', async () => {
await main();
expect(scrape).toHaveBeenCalled();
});
});
此错误为 TypeError: (0 , _index.default) is not a function
我看到 main
不是一个函数,但我还没设法让它工作。
最佳答案
这是我的测试策略,你可以使用jest.mock(moduleName, factory, options)方法模拟 scrape
模块。
index.ts
:
import scrape from './scrape';
const main = (async () => {
return await scrape();
})();
export default main;
index.spec.ts
:
import scrape from './scrape';
import main from './';
jest.mock('./scrape.ts', () => jest.fn().mockResolvedValueOnce('fake data'));
describe('main', () => {
test('should return data', async () => {
const actualValue = await main;
expect(actualValue).toBe('fake data');
expect(scrape).toBeCalledTimes(1);
});
});
100% 覆盖率的单元测试结果:
PASS src/stackoverflow/58674975/index.spec.ts (7.434s)
main
✓ should return data (5ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 8.684s
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58674975
关于unit-testing - 用 Jest 测试自执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58674975/