如何用 jasmine-karma 覆盖函数的所有行

How to cover all lines of a function with jasmine-karma

如何使用 jasmine 覆盖下面函数的所有行?

   addUser(): void {
    if (this.validateNewUser()) {

        this.newUser._Job = this.selectedJob;
        this.newUser.PositionId = this.selectedJob.Id;
        this.newUser.Position = this.selectedJob.Value;

        this.newUser._Area = this.selectedArea;
        this.newUser.AreaId = this.selectedArea.Id;
        this.newUser.Area = this.selectedArea.Value;

        this.users.push(this.newUser);
        this.clear();
        this.toastService.open('Usuário incluído com sucesso!', { type: 'success', close: true });
    }
}

我目前正在尝试如下,但没有任何行被认为是被覆盖的:

    it('Given_addUser_When_UserStepIsCalled_Then_ExpectToBeCalled', (done) => {
        component.addUser = jasmine.createSpy();           
        component.addUser();
        expect(component.addUser).toHaveBeenCalled();
        done();
    });

已编辑

现在: Image here

被测方法(addUser)如果显式调用就不需要检查是否调用了。但是,您应该检查该方法是否完成了它应该做的事情。您可能想知道是否显示了 toast。因此,您可以按如下方式重写测试。

it('#addUser should display toast', () => {

    // given
    spyOn(toastService, 'open');

    // when
    component.addUser();

    // then
    expect(toastService.open).toHaveBeenCalled();
});