用Jest测试自执行功能

时间:2019-11-02 20:22:18

标签: unit-testing testing jestjs

我知道达到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不是一个函数,但是我没有设法使其起作用。

1 个答案:

答案 0 :(得分:0)

这是我的测试策略,您可以使用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