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)
但这并不能说明间谍没有被召唤!
非常感激任何的帮助。
使用spyOn(obj, methodName) \xe2\x86\x92 {Spy}myFunction来监视MyService.prototype.
例如
\nservice.ts:
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}\nRun Code Online (Sandbox Code Playgroud)\nservice.test.ts:
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});\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
5790 次 |
| 最近记录: |