来自组件的角度单元测试spyOn服务

时间:2018-11-26 09:16:28

标签: angular unit-testing karma-runner

我有一个登录组件,我想测试它是否以适当的值调用了服务的方法,但是我不知道如何从该组件中监视该服务。

我尝试过

1.1.3

这不起作用

beforeEach(() => {
...
authService = TestBed.get(AuthService);
});

  

毕竟发生了错误   预期的间谍signInByLogin已使用['test','password']进行了调用,但实际的调用是['','']。

该服务的方法是从登录组件中的私有函数调用的。 电话是

it('should pass proper values', () => {
    const submitSpy = spyOn(authService, 'signInByLogin');
    const loginSpy = spyOn(component, 'signIn').and.callThrough();

    const username = fixture.debugElement.query(By.css('#username'));
    const password = fixture.debugElement.query(By.css('#password'));
    const submitBtn = fixture.debugElement.query(By.css('[type="submit"]'));

    username.nativeElement.value = 'test';
    password.nativeElement.value = 'password';

    fixture.detectChanges();

    expect(username.nativeElement.value).toBe('test');
    expect(password.nativeElement.value).toBe('password');
    expect(submitBtn).toBeTruthy();

    fixture.detectChanges();

    submitBtn.triggerEventHandler('click', null);

    fixture.whenStable().then(() => {
        expect(loginSpy).toHaveBeenCalled();
        expect(submitSpy).toHaveBeenCalledWith('test', 'password');
    });
});

1 个答案:

答案 0 :(得分:0)

间谍工作正常。从错误消息中可以看到,正在调用该服务,但是它是用空字符串而不是输入字段的值来调用的。

您更改了输入的值,但从未发出任何事件,因此Angular不知道值已更改,因此必须修改其模型。您需要添加类似

的内容
username.nativeElement.dispatchEvent(new Event("imput));

(当然,与其他输入相同)。

无耻的插件:这不是必需的,并且如果您使用ngx-speculoos,则测试的代码将更具可读性。

相关问题