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

问题描述

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

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

    constructor() {
       this.myFunction();
    }

    myFunction(){}
}

那我如何测试我的函数调用了?

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

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

it('should demonstrate myFunction called in constructor',() => {
  const spy = spyOn (myService,'myFunction');
  const serv = new myService();

  expect(spy).toHaveBeenCalled();
});

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

我们将不胜感激。

解决方法

使用spyOn(obj,methodName) → {Spy}来监视myFunction上的MyService.prototype

例如

service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',})
export class MyService {
  constructor() {
    this.myFunction();
  }

  myFunction() {}
}

service.test.ts

import { MyService } from './service';

describe('63819030',() => {
  it('should pass',() => {
    const myFunctionSpy = spyOn(MyService.prototype,'myFunction').and.stub();
    const service = new MyService();
    expect(myFunctionSpy).toHaveBeenCalledTimes(1);
  });
});