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*
});
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With