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

34,057

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;
Share:
34,057
thenolin
Author by

thenolin

Angular Enthusiast - Full Stack Angular/.NET Core Developer

Updated on July 09, 2022

Comments

  • thenolin
    thenolin almost 2 years

    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*
    
        });
    
  • Manoj
    Manoj almost 3 years
    expect(result).toBeTruthy(); // it should be toBeTruthy()
  • eyurdakul
    eyurdakul about 2 years
    @Manoj should be expect(result).toBeTrue();