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

試著忘記壹切 提交于 2020-06-12 04:54:57

问题


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 component:

    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*

    });

回答1:


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);
    });

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

return this.object === undefined;


来源:https://stackoverflow.com/questions/55230057/how-to-unit-test-return-value-of-function-angular-jasmine-karma

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!