如何在 Jasmine 中调用假的构造函数

How to call fake a constructor in Jasmine

是否可以像调用函数一样调用 fake 构造函数?

我的class是这样的

class testClass{
     constructor(){
        // to do class member init
        // how to avoid this method call.
        this.method();
     }

     private method() : weird class object {
         // to do method returns weird class object
     }
}

是否可以模拟构造函数并避免调用 this.method()。

我试过像这样创建间谍,但没有成功

jasmine.createSpy('testClass').and.callFake(() =>{})

您可以使用 proxyquire 模拟具有 testClass 的模块。

例如

TestClass.js:

class TestClass {
  constructor() {
    this.method();
  }

  method() {
    console.log('call method');
  }
}

module.exports = TestClass;

然后,我们在某处要求并使用TestClassindex.js:

const TestClass = require('./TestClass');

function main() {
  return new TestClass();
}

module.exports = main;

index.test.js:

const proxyquire = require('proxyquire');

describe('61277026', () => {
  it('should call original TestClass', () => {
    const TestClass = require('./TestClass');
    const logSpy = spyOn(console, 'log').and.callThrough();
    const main = require('./');
    const actual = main();
    expect(actual).toBeInstanceOf(TestClass);
    expect(logSpy).toHaveBeenCalledWith('call method');
  });
  it('should call mocked TestClass', () => {
    const testClassInstance = jasmine.createSpy('testClassInstance');
    const TestClassSpy = jasmine.createSpy('TestClass').and.callFake(() => testClassInstance);
    const main = proxyquire('./', {
      './TestClass': TestClassSpy,
    });
    const actual = main();
    expect(actual).toBe(testClassInstance);
    expect(TestClassSpy).toHaveBeenCalledTimes(1);
  });
});

包含覆盖率报告的单元结果:

Randomized with seed 34204
Started
(node:79855) ExperimentalWarning: The fs.promises API is experimental
call method
..


2 specs, 0 failures
Finished in 0.018 seconds
Randomized with seed 34204 (jasmine --random=true --seed=34204)
---------------|---------|----------|---------|---------|-------------------
File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
---------------|---------|----------|---------|---------|-------------------
All files      |     100 |      100 |     100 |     100 |                   
 TestClass.js  |     100 |      100 |     100 |     100 |                   
 index.js      |     100 |      100 |     100 |     100 |                   
 index.test.js |     100 |      100 |     100 |     100 |                   
---------------|---------|----------|---------|---------|-------------------