测试存根服务

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

在OnInit中,我获取了一些数据的组件:

ngOnInit() {
    this.userService.getUsers().subscribe(users => {
        this.users= users.data;
    });
}

在我的测试中,我存根这项服务:

const UserServiceStub =  {
  getUsers(): Observable<any> {
    return of([{name: 'john doe'}, {name: 'jane doe'}]);
  }
};

我定义了一个供应商:

providers: [ { provide: UserService, useValue: UserServiceStub } ],

现在我想测试呼叫已经作出,而数据元素上设置。

  it('should be initialized with users', fakeAsync(() => {
    const spy = spyOn(UserServiceStub, 'getUsers').and.callThrough();
  }));

它看起来像我可以叫and.returnValue,但我想要的数据来自于短线,我需要设置我的组件的Users属性,以便我可以确认名单在我的模板进行更新。

我不能错过回调callThrough和我没有找到有用的callthough().apply()

如何让我的存根执行?

angular unit-testing jasmine stub
1个回答
1
投票

spy对象可能是错的,你应该得到一个注入服务UserServicespy其方法的实例。

let userService: UserService;
beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [ { provide: UserService, useValue: UserServiceStub } ],
  });
   userService = TestBed.get(UserService);
});

it('should be initialized with users', fakeAsync(() => {
    const spy = spyOn(userService , 'getUsers').and.callThrough();
}));
© www.soinside.com 2019 - 2024. All rights reserved.