我有一个 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
?
您可以为该辅助服务创建一个
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();
});
});