繁体   English   中英

JEST:单元测试 Javascript/Jquery

[英]JEST: Unit testing Javascript/Jquery

嗨,我想使用 Jest 和其中的 click 函数对我的 javascript 代码进行单元测试。

刷卡

export default class swipe {
  constructor() {
    this.init();
  }

  init() {
    this.postRender();
  }

  postRender() {
    const jqry = jQuery.noConflict();
    (function (jqry) {
      jqry(document).ready(() => {
        jqry('#buttonID').on('click', () => {
          jqry('#navigation').addClass('blue');
        });
      });
    })(jqry);
  }
}

这是单元测试解决方案:

swipe.js

import $ from 'jquery';

export default class swipe {
  constructor() {
    this.init();
  }

  init() {
    this.postRender();
  }

  postRender() {
    $(document).ready(() => {
      $('#buttonID').on('click', () => {
        $('#navigation').addClass('blue');
      });
    });
  }
}

swipe.test.js

import Swipe from './swipe';
import $ from 'jquery';

jest.mock(
  'jquery',
  () => {
    const m$ = { on: jest.fn(), ready: jest.fn(), addClass: jest.fn() };
    return jest.fn(() => m$);
  },
  // remove this option if you have installed jquery module
  { virtual: true },
);

describe('60190274', () => {
  it('should add class when click the button', () => {
    $().ready.mockImplementationOnce((callback) => callback());
    $().on.mockImplementationOnce((event, handler) => handler());
    new Swipe();
    expect($).toBeCalledWith(document);
    expect($).toBeCalledWith('#buttonID');
    expect($).toBeCalledWith('#navigation');
    expect($().ready).toBeCalled();
    expect($().on).toBeCalledWith('click', expect.any(Function));
    expect($().addClass).toBeCalledWith('blue');
  });
});

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

 PASS  stackoverflow/60190274/swipe.test.js
  60190274
    ✓ should add class when click the button (6ms)

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

源代码: https : //github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60190274

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM