简体   繁体   English

如何对函数的返回值进行单元测试 - Angular (Jasmine/Karma)

[英]How to unit test return value of function - Angular (Jasmine/Karma)

I am wondering if there is a way to correctly test the return value of a function in Angular.我想知道是否有一种方法可以正确测试 Angular 中函数的返回值。 I want to essentially test the return value to be true for one test and write another to test the opposite scenario.我想基本上测试一个测试的返回值是否为真,并编写另一个测试相反的场景。

Ts component: Ts 组件:

    get() {
        if (this.object == undefined) {
            return true;
        } else {
            return false;
        }    
    }

The only way I can see fit right now to test the return value is to set a variable to hold the return value.我现在认为适合测试返回值的唯一方法是设置一个变量来保存返回值。 Below is my attempt, I'm just stuck on asserting what is to be expected.下面是我的尝试,我只是坚持断言是预期的。

Test:测试:

it('should call get function and return true', () => {
        //Arrange
        component.object = undefined;

        //Act
        component.get();

        //Assert
        expect(component.get). <-- *stuck here*

    });

Get the value in the act and then check it to be true in the assert .获取行为中的值,然后在assert 中检查它是否为true

it('should call get function and return true', () => {
        // Arrange
        component.object = undefined;

        // Act
        var result = component.get();

        // Assert
        expect(result).toBe(true);
    });

On a side note the body of the method get could be simplified to just附带说明一下, get方法的主体可以简化为

return this.object === undefined;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 带有 jasmine karma 的 Angular 单元测试错误(finalSprintsList.map 不是函数) - Angular unit test error ( finalSprintsList.map is not a function ) with jasmine karma 如何使用angular 7 karma / jasmine对@hostlistener粘贴事件进行单元测试 - How to unit test @hostlistener paste event using angular 7 karma/jasmine 如何在 Angular 中使用 Jasmine Karma 对 MatSnackbar 进行单元测试 - How to unit test MatSnackbar using Jasmine Karma in Angular 如何在 Angular 2 Karma Jasmine 中使用 httpheaders 为 http 编写单元测试? - How to write unit test for http with httpheaders in Angular 2 Karma Jasmine? 如何在Angular单元测试Jasmine / Karma中创建ArrayBuffer变量 - How to create an ArrayBuffer Variable in Angular unit test, Jasmine/Karma Angular4-如何使用Karma和Jasmine对指令进行单元测试 - Angular4 - how to unit test a directive using Karma and Jasmine 如何使用 Jasmine /Karma 在 Angular 单元测试中测试 If Else 块 - How to test If Else block in Angular Unit Testing using Jasmine /Karma 如何使用 Angular 中的 Karma-Jasmine 对嵌套的 if 条件进行单元测试? - How to unit test a nested if condition in with Karma-Jasmine in Angular? 如何在 angular6+ 单元测试中等待回调函数(Jasmine+karma) - How to wait for callback function in angular6+ unit test (Jasmine+karma) Angular 2单元测试编译失败茉莉花/业力 - Angular 2 unit test compilation failed jasmine/karma
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM