【问题标题】:Mock an if/else statement with jasmine - unit testing with Angular/Typescript使用 jasmine 模拟 if/else 语句 - 使用 Angular/Typescript 进行单元测试
【发布时间】:2021-02-16 02:16:16
【问题描述】:

我在现有功能中添加了一个小修改。我们的质量检查已将其识别为新代码,因此我需要用单元测试覆盖新的 4 行 - 请记住,从一开始就没有单元测试,而且我添加的功能非常大!

我尝试了多种方法来尝试模拟服务、变量、间谍等...但总是出错。我是茉莉花的新手,所以很挣扎。我需要做的就是进行任何形式的检查以涵盖真假。

component.ts 文件

hasDescription() {
        return this.isBrilliant() || this.isCool();
    }

isBrilliant() {
        return this.service.Type.description == 'Brilliant';
    }

isCool() {
        return this.service.Type.description == 'Cool';
    }



onExportToExcel(): void {
        var r = [];
        // added the below if/else - any check on this will be suffice.
        if (this.hasDescription()) {
            if (!this.isBrilliant()) {
                r.push('This is Cool');
            } else {
                r.push('This is Brilliant');
            }
            if (!this.isBrilliant()) {
            r.push('More Cool content');
            }
        }
}

我尝试将isBrilliant() 设置为模拟值true,并期望该值是真实的expect(component.isBrilliant()).toBeTruthy();

我尝试通过以下方式在规范文件中进行设置:

const isBrilliant = true;
component.isBrilliant = isBrilliant;

但是我在这里遇到的错误是Type 'true' is not assignable to type '() => boolean'.

如果有经验丰富的 jasmine 开发人员可以向我展示一种快速了解这个简单语句的方法,我将不胜感激。谢谢


更新

我可以得到isBrilliant() 的真假。我现在需要检查数组 r 以查看正确的字符串是否已将 .push 放入其中?有什么想法吗?

【问题讨论】:

  • 试试const isBrilliant = () => true
  • 如果这不起作用,我可能会将service.Type.description 模拟为'Brilliant'
  • 感谢@ShamPooSham 帮助我克服了分配错误。您能就“更新”提出建议吗?
  • 很难/如果不是不可能在 Jasmine 中处理 r,因为它是 onExportToExcel 的本地地址。拨打onExportToExcel时,它有什么作用?它会改变视图吗?如果是这样,请测试一下。明确地调用它,并确保它完成它的最终产品。
  • onExportToExcel 似乎没有像现在这样做任何事情。没有任何东西被导出,没有状态被改变。正如 AliF50 所说,你应该想想你想用它做什么。

标签: javascript angular typescript unit-testing karma-jasmine


【解决方案1】:

作为最佳实践的一部分,我建议进行一些更改。

  1. 不要模拟组件方法,因为你需要测试它们。在您的情况下,您应该设置this.service.Type.description 的值,因此它应该返回truefalse。那将是一个正确的方法。

如果this.service 是在construtor 上注入的服务,您可以模拟该服务。参考this article to understand mocking here

  1. 由于您使用 if else 测试多个条件,因此您需要编写少量 it 块以获得良好的测试覆盖率。

  2. 要测试 var r ,您应该在组件级别将其声明为 public 变量,而不是在 function 内。也更喜欢let 而不是var

这是一个示例代码,您可以编写它来设置isBrilliant()中的值

it('should push Brilliant when the Description is so,()=>{
   component.service.Type.description = 'Brilliant';
   component.onExportToExcel();
   expect(component.r.length).toBe(1);
   expect(component.r[0]).toBe('This is Brilliant');
})

it('should push other cool content when the Description is not Brilliant,()=>{
   component.service.Type.description = 'something else';
   component.onExportToExcel();
   expect(component.r.length).toBe(2);
   // check other values in expect block accordingly
})

// you should also check that "component.r" has zero length when hasDescription() returns false

希望上面的代码sn-p能给你一个好的开始

【讨论】:

    猜你喜欢
    • 2021-10-13
    • 2015-09-01
    • 1970-01-01
    • 2017-01-22
    • 2016-08-14
    • 2016-08-16
    • 2023-01-13
    • 1970-01-01
    • 2017-06-23
    相关资源
    最近更新 更多