如何对服务构造函数中调用的函数进行单元测试?

sup*_*guy 1 service unit-testing jasmine karma-runner angular

如何在服务的规范文件中测试构造函数中调用的函数?例如:

@Injectable({
    providedIn: 'root'
})
export class myService {
  

    constructor() {
       this.myFunction();
    }

    myFunction(){}
}
Run Code Online (Sandbox Code Playgroud)

那么我如何测试我的函数是否被调用呢?

beforeEach(() => {
TestBed.configureTestingModule({});
    service = TestBed.get(myService);

Run Code Online (Sandbox Code Playgroud)

我无法在 testbed.get 之前监视服务,我尝试过:

beforeEach(() => {
TestBed.configureTestingModule({});
    service = TestBed.get(myService);

Run Code Online (Sandbox Code Playgroud)

但这并不能说明间谍没有被召唤!

非常感激任何的帮助。

sli*_*wp2 5

使用spyOn(obj, methodName) \xe2\x86\x92 {Spy}myFunction来监视MyService.prototype.

\n

例如

\n

service.ts:

\n
import { Injectable } from \'@angular/core\';\n\n@Injectable({\n  providedIn: \'root\',\n})\nexport class MyService {\n  constructor() {\n    this.myFunction();\n  }\n\n  myFunction() {}\n}\n
Run Code Online (Sandbox Code Playgroud)\n

service.test.ts:

\n
import { MyService } from \'./service\';\n\ndescribe(\'63819030\', () => {\n  it(\'should pass\', () => {\n    const myFunctionSpy = spyOn(MyService.prototype, \'myFunction\').and.stub();\n    const service = new MyService();\n    expect(myFunctionSpy).toHaveBeenCalledTimes(1);\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n