开玩笑地为addEventListener编写单元测试时遇到麻烦

时间:2020-02-01 07:26:51

标签: javascript unit-testing dom jestjs

我想为以下功能编写一个玩笑的单元测试,所以出现错误

 const variableski = document.querySelector('.skipnav');

 variableski.addEventListener('click', () => {
      this.somefunction();
    });

1 个答案:

答案 0 :(得分:1)

这是单元测试解决方案:

index.js

class SomeClass {
  skipToBotHandler() {
    const skipNav = document.querySelector('.skipnav');

    skipNav.addEventListener('click', () => {
      this.skipLinkFocusHandler();
    });
  }

  skipLinkFocusHandler() {}
}

export { SomeClass };

index.test.js

import { SomeClass } from './';

describe('60014903', () => {
  afterEach(() => {
    jest.restoreAllMocks();
    jest.resetAllMocks();
  });
  it('should pass', () => {
    jest.spyOn(SomeClass.prototype, 'skipLinkFocusHandler');
    const mSkipNav = {
      addEventListener: jest.fn().mockImplementationOnce((event, handler) => {
        handler();
      }),
    };
    document.querySelector = jest.fn().mockReturnValueOnce(mSkipNav);
    const instance = new SomeClass();
    instance.skipToBotHandler();
    expect(document.querySelector).toBeCalledWith('.skipnav');
    expect(mSkipNav.addEventListener).toBeCalledWith('click', expect.any(Function));
    expect(instance.skipLinkFocusHandler).toBeCalledTimes(1);
  });
});

单元测试结果覆盖率100%:

 PASS  src/stackoverflow/60014903/index.test.js (10.203s)
  60014903
    ✓ should pass (9ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.js |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        11.538s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/60014903