Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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*

    });
like image 325
thenolin Avatar asked Mar 18 '19 21:03

thenolin


People also ask

How do you write unit test cases in Angular using Jasmine?

Create an Angular project with jasmine and karma By doing this, the jasmine and karma configuration is resolved for us. Install and create a new project with angular-cli: Install npm -g @angular/cli. Ng new angular-unit-testing angular unit-testing.

How do you use karma in Jasmine test cases?

We can run Jasmine tests in a browser ourselves by setting up and loading a HTML file, but more commonly we use a command-line tool called Karma. Karma handles the process of creating HTML files, opening browsers and running tests and returning the results of those tests to the command line.

Is Karma used for unit testing?

When it comes to tools used in Angular unit testing—or even vanilla JavaScript testing, for that matter—no tool is better known than Karma (sometimes also called “Karma JS.”) Karma is a testing tool developed by the AngularJS team, so it's understandable why it's usually associated with the framework.


1 Answers

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;
like image 172
Igor Avatar answered Sep 20 '22 13:09

Igor