测试子类的方法

问题描述 投票:0回答:1

[我正在尝试测试类A的方法X调用导入的函数Y。类A是类B的子类,应该对其进行模拟。

A类看起来像这样:

const B = require('./B');
const { Y } = require('../util');
class A extends B {
  constructor() {
    super('/A');
    this.setCors('');
    this.app.post('', this.X.bind(this));
  }

  X(req, res) {
    Y();
  }
}

module.exports = A;

尝试测试(Jest Official Docs之后:]

const A = require('../path/to/A');
const B = require('../path/to/B');
jest.mock('../path/to/B', () => {
  return jest.fn().mockImplementation(() => {
    return { setCors: jest.fn(), app: { post: jest.fn() } };
  });
});

test('method X calls function Y', () => {
  (new A()).X();
  expect(Y).toBeCalled();
});

这将给出关于A的构造函数的错误TypeError: Cannot read property 'bind' of undefined。>>

也许只需要模拟出构造函数,但是我不确定该怎么做。

[我正在尝试测试类A的方法X调用导入的函数Y。类A是类B的子类,应将其模拟出来。 A类看起来像这样:const B = require('./ B'); const {Y} = ...

javascript jestjs es6-class
1个回答
0
投票

这里是解决方法:

© www.soinside.com 2019 - 2024. All rights reserved.