首页 > 解决方案 > Jasmine 模拟调用服务而不是模拟值

问题描述

我有这个方法,它在里面调用一个服务。

searchUser() {
    this.isLoading = true;
    this.usersService.searchEmailandName(this.corporateId.value).subscribe(
        (data: UserSearch) => {
            this.isLoading = false;
            this.email.patchValue(data.email);
            this.name.patchValue(data.name);
            this.checkInputs();
        }, error => {
            this.isLoading = false;
            this.errorGeneric.errorGeneric(error, 'search_user');
            this.email.patchValue('');
            this.name.patchValue('');
        }
    );
}

我正在尝试正确测试它:

it('should test searchUser ', (done) => {
    usersService = TestBed.get(UsersService);

    component.corporateId.patchValue(userProfile.user.corporateId);
    component.searchUser();
    spyOn(usersService, 'searchEmailandName').and.returnValue(of(userProfile.user));

    expect(component.email.value).toBe('mock name');
    expect(component.name.value).toBe('mock@email.com');
    done();
});

用户个人资料包含我需要嘲笑的所有信息。我收到此错误

Error: Expected undefined to be 'mock name'.

所以我可能没有正确地做间谍,或者只是误解了它是如何工作的

标签: angularjasminekarma-jasmine

解决方案


spyOn在调用该方法之前尝试执行。

it('should test searchUser ', (done) => {
    usersService = TestBed.get(UsersService);

    component.corporateId.patchValue(userProfile.user.corporateId);
    // spy first before calling the method
    spyOn(usersService, 'searchEmailandName').and.returnValue(of(userProfile.user));
    component.searchUser();

    expect(component.email.value).toBe('mock name');
    expect(component.name.value).toBe('mock@email.com');
    done();
});

推荐阅读