unit-testing - 用 Jest 测试自执行函数

标签 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 不是一个函数,但我还没设法让它工作。

最佳答案

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

相关文章:

angularjs - 如何测试 Angular 事件?

unit-testing - 为什么我的 HUnit 测试套件失败但在 Cabal 中成功通过?

unit-testing - 如何运行多个 Groovy 单元测试

testing - 如何实现集成测试以检查我的断路器回退是否被调用?

java - 对 Controller 进行单元测试

Angular 11 : Unit testing an HttpInterceptor - can't get catchError to work in test

javascript - 如何在 Mocha/Chai 中测试 JS 原型(prototype)(非模块)?

unit-testing - 使用 Vuex 的 Vue.js-electron 应用程序的设置测试

javascript - 如何设置 Jest 来测试 Canvas

reactjs - 在 Contenteditable 元素上触发事件 keyDown(测试 + react + Jest + enzyme )