【问题标题】:Jest : mock constructor function笑话:模拟构造函数
【发布时间】:2020-10-16 02:14:35
【问题描述】:

我在尝试模拟构造函数时遇到问题。

这是我要测试的主要类

// 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 不是执行 new Handler() 的行上的构造函数。当它是构造函数时,我如何模拟新的 Handler 调用

【问题讨论】:

  • 为什么不直接使用模拟实现?

标签: javascript jestjs mocking


【解决方案1】:

您可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多