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

How to unit test function called in service's constructor?

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

@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} 监视 MyService.prototype 上的 myFunction

例如

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);
  });
});