Using Jasmine to simulate an if/else statement in Angular/Typescript unit testing

After making a minor change to an existing function, it has been flagged as new code during our quality checks. This means I need to create a unit test specifically for the new 4 lines of code. The challenge is that there was never a unit test in place for this function which happens to be quite large!

I've attempted various methods such as mocking services, variables, and spying but I keep running into errors. Being relatively new to jasmine, I am finding it challenging. All I really want to do is create some kind of check to validate the truthiness or falsiness of those added lines.

component.ts file

hasDescription() {
        return this.isBrilliant() || this.isCool();
    }

isBrilliant() {
        return this.service.Type.description == 'Brilliant';
    }

isCool() {
        return this.service.Type.description == 'Cool';
    }



onExportToExcel(): void {
        var r = [];
        // added the below if/else - any check on this will be suffice.
        if (this.hasDescription()) {
            if (!this.isBrilliant()) {
                r.push('This is Cool');
            } else {
                r.push('This is Brilliant');
            }
            if (!this.isBrilliant()) {
            r.push('More Cool content');
            }
        }
}

I attempted to set isBrilliant() with a mock value of true, expecting the value to be truthy

expect(component.isBrilliant()).toBeTruthy();

In the spec file, I tried:

const isBrilliant = true;
component.isBrilliant = isBrilliant;

However, this resulted in an error stating

Type 'true' is not assignable to type '() => boolean'.

If any experienced jasmine developer could provide me with a simple solution to achieve some coverage for this straightforward statement, I would greatly appreciate it. Thank you


UPDATE:

I have managed to set isBrilliant() to be true or false. Now, I need to verify whether the correct string has been pushed into the array r? Any suggestions?

Answer №1

Here are some recommended changes to follow best practices:

  1. Avoid mocking component methods, as it is important to test them. Instead, set the value of this.service.Type.description and ensure that it correctly returns either true or false.

If this.service is a service injected in the constructor, you can mock the service. Refer to this article for more information on mocking

  1. When testing multiple conditions using if else, make sure to write multiple it blocks to achieve comprehensive test coverage.

  2. To test var r, declare it as a public variable at the component level rather than inside a function. It's also preferable to use let instead of var.

Below is a sample code snippet demonstrating how to set values in isBrilliant():

it('should push Brilliant when the Description is so,()=>{
   component.service.Type.description = 'Brilliant';
   component.onExportToExcel();
   expect(component.r.length).toBe(1);
   expect(component.r[0]).toBe('This is Brilliant');
})

it('should push other cool content when the Description is not Brilliant,()=>{
   component.service.Type.description = 'something else';
   component.onExportToExcel();
   expect(component.r.length).toBe(2);
   // check other values in expect block accordingly
})

// Also, ensure to check that "component.r" has zero length when hasDescription() returns false

I trust that the provided code snippet will serve as a helpful starting point for you

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to group a Pie Chart by a string field in a .csv file using dc.js, d3.js, and crossfilter.js in a Node environment?

I've successfully set up several Dimensions and groups, but I'm encountering an issue with a Pie Chart that needs to be grouped based on domain names like bing.com. Each domain name is parsed consistently to xxxx.xxx format and the data is clean. ...

Guide to creating several AJAX requests using a for loop

I'm currently experimenting with the Star Wars API (SWAPI) and attempting to display the names of all the planets. However, the planet information is spread across multiple pages. How can I go about making several AJAX requests in order to retrieve an ...

Nuxt - Issue persisting logged in state on refresh despite information being stored in local storage and cookies

I am facing an issue where the state gets cleared on refresh, even though the token, userid, user email, and expiration date are stored in local storage and cookies. I suspect there might be a problem with the store or something else needs to be done to re ...

Creating a reset or refresh button with JavaScript: Step-by-step guide

Can someone please help me figure out how to create a button that will refresh the page while also resetting all values to their default settings? ...

Serve the mobile version to mobile visitors and the desktop version to all other visitors

Can someone please explain to me how I can display the Mobile Version of a website when visiting on my phone, and the Desktop Version when viewing on anything larger than 500px? I have separately created both a Mobile Website and a Desktop Website. Is it ...

After being deployed on Vercel, React is mistakenly redirecting to the incorrect file, although it functions properly when

I'm a beginner in JavaScript and I recently created a React project. Everything was working smoothly in local development until I deployed the project on Vercel. The issue is when a user clicks on the "about button," instead of showing 'about.htm ...

Retrieving all records in Firestore that have access to their child documents

I'm attempting to retrieve all the documents from each child collection (ratings) and update the average rating in the foobar document. However, I am encountering an error in one of my callable functions: Unhandled error RangeError: Maximum call stack ...

What is the distinction between selecting and entering a date input value?

When a user selects a date, it needs to be immediately sent to the server. If they manually type in the date, it should be sent on blur. The issue arises when the oninput event is triggered for each keydown event, causing unnecessary server requests while ...

Tips for generating JSON data in the correct format dynamically while continuously adding new information to the existing object

In my form, users input their email and password, which then generates dynamic JSON upon submission. However, I encountered an issue where the JSON gets corrupted when logging in with different user details as it updates the existing JSON with a new object ...

When the document is fully loaded and processed, a script will be executed immediately following

I'm facing an issue with a modal plugin on my website. The plugin is triggered on $(document).ready, but I have another function (innerHTML) that inserts an <a> element 5-10 seconds after the page loads. This causes the modal not to work properl ...

What is the best way to apply a specific style based on the book ID or card ID when a click event occurs on a specific card in vue.js

My latest project involves creating a page that displays a variety of books, with the data being fetched from a backend API and presented as cards. Each book card features two button sections: the first section includes "ADD TO BAG" and "WISHLIST" buttons ...

Angular 2's HTTP post method encountering issues

Currently, I am attempting to implement a post method utilizing AngularJS 2 HTTP. The REST call I am using is shown below: saveCourse(Course: any) { let url ='https://server/CoursesWebApi/api/courses/insert'; let headers = new Headers() ...

Transforming file location to base64 encoded format using TypeScript

I have the path of an image and need to convert it to base64 format, similar to this data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUg... function encodeImageToBase64(url, callback) { var xhr = new XMLHttpRequest(); xhr.onload = function() { va ...

Is it possible to assign a deconstructed array to a variable and then further deconstruct it?

Is there a way to deconstruct an array, assign it to a variable, and then pass the value to another deconstructed variable all in one line of code? Take a look at what I want to achieve below: const { prop } = [a] = chips.filter(x => x.id == 1); Typic ...

An Unexpected ER_BAD_FIELD_ERROR in Loopback 4

I encountered an unusual error: Unhandled error in GET /managers: 500 Error: ER_BAD_FIELD_ERROR: Unknown column 'role_id' in 'field list' at Query.Sequence._packetToError (/Users/xxxx/node_modules/mysql/lib/protocol/se ...

How come certain rectangles vanish when one rectangle completely fills the space?

Currently, I am encountering an issue with CSS paint worklet and I am trying to determine if it's a browser bug or an error on my end. In the worklet, I am drawing multiple rectangles. Strangely, when one rectangle covers the entire area, the others s ...

Is there a way to implement a watch on $validator.errors in Vue.js using the Vee Validation plugin?

My intention was to implement a watch on $validator.errors, so that any error that arises gets logged, To achieve this, I checked the length of errors and stored self.errors.all() in a variable, However, I'm curious if it's possible to directly ...

Leaving a message on someone else's Facebook wall by sharing a link to a website

I've been trying to figure this out, but I honestly have no idea where to start. Twitter has a feature that allows a link to open a box where users can write a tweet and post it directly to their chosen feed: It's really simple, just changing t ...

What could be the reason behind the malfunction of this jQuery post request?

I am currently studying AJAX with jQuery, but I am facing an issue with my registration system. The following code does not seem to work: $('#submitr').click(function () { var username = $('#usernamefieldr').val(); var password ...

Implementing automatic selection mode in Kendo MVC grid

Seeking to modify the SelectionMode of a Kendo MVC Grid, I aim to switch from single to multiple using Javascript or JQuery upon checkbox selection, and revert back when the checkbox is unchecked. Is this feasible? Additionally, I am successfully binding a ...