代码之家  ›  专栏  ›  技术社区  ›  RSeidelsohn

如何测试类列表。使用Jest添加/删除?

  •  3
  • RSeidelsohn  · 技术社区  · 8 年前

    不管怎么做,我怎么能测试这样的函数:

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

    切换类 类列表。广告/删除 是否已被调用? 我尝试过这样设置模拟函数:

    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)
    

    1 回复  |  直到 6 年前
        1
  •  7
  •   Lin Du Correcter    6 年前

    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');
      });
    });
    

     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