Mocha JS-模拟父类模块

Mocha JS - mock parent class module

本文关键字:模块 父类 模拟 JS- Mocha      更新时间:2023-09-26

背景

我有从类B:扩展而来的类A

A = class A
    ...
    my_inner_func: (param1) =>
        return new MyHelper()
B = class B extends A
    ...

我想做什么

在单元测试中,my_inner_func()应该返回MyMockHelper()

我尝试过的

a = rewire './a.coffee'
b = rewire './b.coffee'
a.__set__
    MyHelper: MyMockHelper
b.__set__
    A: a.A

但是B().my_inner_func()返回MyHelper而不是MyMockHelper

我的问题

如何模拟CoffeeScript(或JavaScript(中扩展类使用的模块?

rewire的文档没有说明类实例变量。我认为这实际上只是为了"重新连接"被测试模块的全局或顶级范围。

此外,重新布线也有一些局限性。其中,对const或babel的支持似乎是ify,所以也许可以尝试本地解决方案?

在基本级别上,mock只是覆盖或替换对象原型上的方法,所以类似的东西应该在您的测试用例中工作

// super class
class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  get area() {
    return this.calcArea();
  }
  calcArea() {
    return this.height * this.width;
  }
}
// superclass instance
const rect = new Polygon(10, 2);
console.log('rect', rect.area); // 20
// subclass
class Square extends Polygon {
  constructor(side) {
    super(side, side)
  }
}
// subclass instance
const square = new Square(2);
console.log('square', square.area); // 4
// mocked calcArea of subclass
square.calcArea = function() {
    return 0;
};
// result from new mocked calcArea
console.log('mocked', square.area); // 0

使用摩卡可能看起来像这样。。。

import Square from './Square';
describe('mocks', () => {
    it('should mock calcArea', () => {
        const square = new Square(2);
        square.calcArea = function() {
            return 0;
        };
        expect(square.area).to.equal(0);
    });
});

这里有一支代码笔可以用来玩