出于单元测试目的覆盖对象属性

Rey*_*edy 8 javascript object-properties typescript jestjs

我正在使用 Jest 在 Node.js 应用程序上执行单元测试,其中代码源是用 TypeScript 编写的,然后编译为 JavaScript。

在我希望测试的一个类中,导入了一个外部模块并使用了该模块中的方法。我想模拟对此方法的调用,以便仅测试我的代码。

但是,当我运行测试时,出现以下错误:

TypeError: Cannot redefine property: methodName

问题是该方法具有以下对象属性:

{ value: [Function],
  writable: false,
  enumerable: true,
  configurable: false }
Run Code Online (Sandbox Code Playgroud)

configurable: false就是它成为一个大问题的原因。我无法在模拟调用之前重新定义属性以使其可写。

相关代码如下:

测试类

import externalType from 'external-module-name';

export class ClassName {
    public propertyName: externalType;

    public method(param: string): Promise<any> {
        return new Promise((resolve, reject) => {
            this.propertyName.externalMethod(param)
            .then((res) => {
                resolve(res);
            })
            .catch((err) => {
                reject(err);
            });
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

单元测试

import { ClassName } from 'path/to/class';

describe('class', () => {
    const class = new ClassName;

    it("Blahblah", (done) => {
        Object.defineProperty(class['propertyName'], 'externalMethod', {writable: true});
        const spy = jest.spyOn(class['propertyName'], 'externalMethod').mockReturnValue(Promise.resolve());
        class.method('string')
        .then((result) => {
            // Various expect()
            done();
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

到目前为止我尝试过的

  1. 我在测试中添加了以下行:

    Object.defineProperty(class['module'], 'methodName', {writable: true});

  2. 我将模拟调用定义如下:

    jest.spyOn(class['module'], 'methodName').mockReturnValue(Promise.resolve());

  3. 我将模拟调用定义如下:

    class.propertyName.externalMethod = jest.fn().mockImplementation((query) => { return Promise.resolve(); });

  4. 我尝试覆盖我正在调用的属性,如下所示:

    class.propertyName = <any> { externalMethod = (param: any) => { return Promise.resolve(); } }

对于这一点,我得到了错误TypeError: Cannot assign to read only property externalMethod of object class,这是有道理的,因为可读设置为 false。

但一切似乎都被属性封锁了configurable。我确信有一些事情可以做,因为我可能不是唯一一个想要对导入外部模块的类执行单元测试的人,尽管它很安全。

所以我的问题是:模拟外部方法的干净且有效的方法是什么?如果这是绝对不可能的,那么在不调用外部方法的情况下测试我的类的方法是什么?

提前致谢!

Guy*_*Guy 8

我发现通过这样做:

jest.mock('path/to/class');
Run Code Online (Sandbox Code Playgroud)

我能够解决这个问题。


ang*_*gie 0

这有点像黑客,但在我有一个更干净的解决方案之前,以下是可以接受的权宜之计:

let override: boolean | undefined;

static before() {
    Object.defineProperty(module, 'readonlyProperty', {
        get() {
            return this.override;
        }
    });
}

@test
public test() {
    this.override = false;
    expect(module.readonlyProperty).to.be.false;
}
Run Code Online (Sandbox Code Playgroud)

- - 更新 - -

如果使用 sinon 沙箱,请使用replaceAPI

const sandbox = sinon.createSandbox();
sandbox.replace(module, 'readonlyProperty', false);
Run Code Online (Sandbox Code Playgroud)