如何对函数的返回值进行单元测试-Angular(Jasmine/Karma) [英] How to unit test return value of function - Angular (Jasmine/Karma)

查看:74
本文介绍了如何对函数的返回值进行单元测试-Angular(Jasmine/Karma)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以正确测试Angular中函数的返回值.我想本质上测试一个测试的返回值为true,然后编写另一个测试相反的场景.

I am wondering if there is a way to correctly test the return value of a function in Angular. I want to essentially test the return value to be true for one test and write another to test the opposite scenario.

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.

测试:

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

        //Act
        component.get();

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

    });

推荐答案

act 中获取值,然后在 assert 中将其检查为true.

Get the value in the act and then check it to be true in the assert.

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

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

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


请注意,方法get的主体可以简化为


On a side note the body of the method get could be simplified to just

return this.object === undefined;

这篇关于如何对函数的返回值进行单元测试-Angular(Jasmine/Karma)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆