简体   繁体   English

Jest:模拟构造函数

[英]Jest : mock constructor function

I'm having trouble trying to mock a constructor Function.我在尝试模拟构造函数时遇到问题。

Here is the main class that I want to test这是我要测试的主类

// main.js

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

Here is how my Handler function looks.这是我的 Handler 函数的外观。 Im trying to mock this我试图嘲笑这个

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

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

And the test code:和测试代码:

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

I referred this stack overflow and tried but now Im getting error like _handler.Handler is not a constructor on the line that does new Handler().我提到了这个堆栈溢出并尝试过,但现在我收到错误,如 _handler.Handler is not a constructor on the line that do new Handler()。 How can I mock the new Handler call when its a constructor function当它是一个构造函数时,我如何模拟新的 Handler 调用

You could use jest.mock(moduleName, factory, options) to mock ./handler/handler.js module and Handler class manually.您可以使用jest.mock(moduleName, factory, options)手动模拟./handler/handler.js模块和Handler类。

Eg例如

main.js : main.js :

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

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

handler/handler.js : handler/handler.js

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

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

main.test.js : 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');
  });
});

unit test result:单元测试结果:

 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

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

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