如何在角度单元测试中监视服务构造函数中的嵌套方法

问题描述 投票:0回答:1

我有一个 Angular 服务,它依赖于另一个服务,该服务有一个属性,它是一个包含我想要监视的方法的对象。

@Injectable({
    providedIn: 'root'
})
export class MyService {
    constructor(
        private secondService:SecondService,
    ) {
        this.secondService.someObj.someMethod();
    }
}
@Injectable({
    providedIn: 'root'
})
export class SecondService {
    someObj = {
        someMethod: () => {
            //do stuff
        }
    }
}

测试时如何监视

someMethod
MyService

angular unit-testing mocking jasmine karma-jasmine
1个回答
0
投票

您可以为该辅助服务创建一个

createSpyObj
,其中第一个参数是服务模拟名称,第二个参数是方法,第三个参数是属性。

describe('MyService', () => {
  let service: MyService;
  let mockValidator: jasmine.SpyObj<SecondService>;
  const someObj = {
                someMethod: () => {
                      //do stuff
                }
          };
  beforeEach(() => {
    spyOn<any>(someObj, 'someMethod');
    TestBed.configureTestingModule({
      providers: [
        DataService,
        { provide: ValidationService, useValue: jasmine.createSpyObj('SecondService', [], 
          {'someObj': someObj  }) 
        }
      ]
    });

    service = TestBed.get(MyService);
    secondService = TestBed.get(SecondService);
  });

  it('someMethod should be called on constructor', () => {
    expect(someObj.someMethod).toHaveBeenCalled();
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.