Jasmine 模拟服务调用不模拟值

Jasmine mock call to service not mocking values

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

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'.

所以我可能没有正确地进行间谍活动,或者只是误解了它的工作原理

尝试在调用该方法之前执行 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();
});