【问题标题】:How to cover all lines of a function with jasmine-karma如何用 jasmine-karma 覆盖函数的所有行
【发布时间】:2020-04-04 16:48:38
【问题描述】:

如何使用 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

【问题讨论】:

    标签: jasmine karma-jasmine karma-coverage jasmine2.0


    【解决方案1】:

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

    it('#addUser should display toast', () => {
    
        // given
        spyOn(toastService, 'open');
    
        // when
        component.addUser();
    
        // then
        expect(toastService.open).toHaveBeenCalled();
    });
    

    【讨论】:

    • 酷,它在某些方面有效,但并非适用于所有方面,因为我可以涵盖所有方面,我发送了问题中的照片
    • 显然this.validateNewUser()返回false,由你自己找出原因。
    • 你能帮助另一个返回承诺的函数吗?
    • @ Guilherme Prado:请为新问题发布新问题。
    • @uminder,我在这里发帖stackoverflow.com/questions/59306897/…
    猜你喜欢
    • 2014-06-06
    • 2020-04-05
    • 2016-02-29
    • 2022-10-20
    • 2016-01-22
    • 2020-06-02
    • 1970-01-01
    • 2016-04-02
    相关资源
    最近更新 更多