【问题标题】:How to call fake a constructor in Jasmine如何在 Jasmine 中调用伪造的构造函数
【发布时间】:2020-04-17 17:11:31
【问题描述】:

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

我的课是这样的

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(() =>{})

【问题讨论】:

  • 我不相信你能做到。你必须创建一个模拟类。
  • 喜欢MockClass,然后在providers中提供
  • 是的,完全正确。我不认为你可以劫持构造函数。
  • 好的,会试试的,谢谢

标签: angular unit-testing testing jasmine karma-jasmine


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-20
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    相关资源
    最近更新 更多