如何使用Jest测试classList.add / remove?

时间:2017-08-28 11:55:21

标签: jestjs

根本不考虑使用它,我该如何测试这样的函数:

export const toggleClass = (elementDOM, className) => {
    if (elementDOM.classList.contains(className)) {
        elementDOM.classList.remove(className);
    } else {
        elementDOM.classList.add(className);
    }
};

我当然可以在每次调用 toggleClass 之后创建一个DOM元素并检查className属性,但是如何测试是否已调用 classList.ad/remove ? 我尝试过设置这样的模拟函数:

const addSpy    = jest.fn();
const removeSpy = jest.fn();
Element.prototype.classList = {
    add   : addSpy,
    remove: removeSpy,
};

但这只会产生以下错误消息:

TypeError: Cannot read property 'classList' of undefined

  at Node.get [as classList] (node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/generated/Element.js:450:46)
  at Object.<anonymous> (app/Resources/scripts/helper/utils.test.js:23:37)
  at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
  at process._tickCallback (internal/process/next_tick.js:109:7)

我是否缺乏对Jest或测试概念的理解,或者这是不可行的?

1 个答案:

答案 0 :(得分:2)

这是基于@Or B的评论的完整解决方案:

index.ts

export const toggleClass = (elementDOM, className) => {
  if (elementDOM.classList.contains(className)) {
    elementDOM.classList.remove(className);
  } else {
    elementDOM.classList.add(className);
  }
};

index.spec.ts

import { toggleClass } from '.';

describe('toggleClass', () => {
  const mockedElementDOM = { classList: { contains: jest.fn(), remove: jest.fn(), add: jest.fn() } };

  it('should remove the class', () => {
    const className = 'a';
    mockedElementDOM.classList.contains.mockReturnValueOnce(true);
    toggleClass(mockedElementDOM, className);
    expect(mockedElementDOM.classList.remove).toBeCalledWith('a');
  });

  it('should add the class', () => {
    const className = 'a';
    mockedElementDOM.classList.contains.mockReturnValueOnce(false);
    toggleClass(mockedElementDOM, className);
    expect(mockedElementDOM.classList.add).toBeCalledWith('a');
  });
});

具有100%覆盖率报告的单元测试结果:

 PASS  src/stackoverflow/45918386/index.spec.ts
  toggleClass
    ✓ should remove the class (4ms)
    ✓ should add the class (1ms)

----------|----------|----------|----------|----------|-------------------|
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:       2 passed, 2 total
Snapshots:   0 total
Time:        3.575s, estimated 9s

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