简体   繁体   中英

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. 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(). How can I mock the new Handler call when its a constructor function

You could use jest.mock(moduleName, factory, options) to mock ./handler/handler.js module and Handler class manually.

Eg

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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