开玩笑:模拟构造函数

时间:2020-10-16 02:14:35

标签: javascript jestjs mocking

尝试模拟构造函数时遇到麻烦。

这是我要测试的主要课程

// main.js

import { Handler } from './handler/handler.js';
var lh = new Handler(windowAlias, documentAlias);
   // rest of code

这是我的Handler函数的外观。我试图嘲笑这个

//handler.js
export function Handler(windowAlias, documentAlias) {
  this.windowAlias = windowAlias;
  this.documentAlias = documentAlias;

  this.attachEventListners = function(globalSet) {
    // do something
  };
}

测试代码:

// main.test.js
   import { Handler } from 'handlers/handler'

   describe('main script', () => {

       it('test handler', () => {
            jest.mock('handlers/handler', () => jest.fn())
            const mockEventListner = jest.fn()
            Handler.mockImplementation(() => ({mockEventListner}))

            //call main.js

            expect(mockEventListner).toBeCalledTimes(1);
})

我引用了this堆栈溢出并尝试过,但是现在我收到类似_handler.Handler的错误消息,Handler不是执行new Handler()的行上的构造函数。当新的Handler调用使用构造函数时,该如何模拟呢?

1 个答案:

答案 0 :(得分:2)

您可以使用jest.mock(moduleName, factory, options)手动模拟./handler/handler.js模块和Handler类。

例如

main.js

import { Handler } from './handler/handler.js';

const windowAlias = 'windowAlias';
const documentAlias = 'documentAlias';
var lh = new Handler(windowAlias, documentAlias);

handler/handler.js

export function Handler(windowAlias, documentAlias) {
  this.windowAlias = windowAlias;
  this.documentAlias = documentAlias;

  this.attachEventListners = function(globalSet) {
    // do something
  };
}

main.test.js

import './main';
import { Handler } from './handler/handler.js';
jest.mock('./handler/handler.js', () => {
  return { Handler: jest.fn() };
});

describe('64382021', () => {
  it('should pass', async () => {
    expect(Handler).toBeCalledWith('windowAlias', 'documentAlias');
  });
});

单元测试结果:

 PASS  src/stackoverflow/64382021/main.test.js
  64382021
    ✓ should pass (6ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.093s, estimated 10s