Tips on how to effectively unit test error scenarios when creating a DOM element using Angular

I designed a feature to insert a canonical tag.

Here is the code for the feature:

  createLinkForCanonicalURL(tagData) {
    try {
      if (!tagData) {
        return;
      }
      const link: HTMLLinkElement = this.dom.createElement('link');

      Object.keys(tagData).forEach((prop: string) => {
        link.setAttribute(prop, tagData[prop]);
      });

      this.dom.head.appendChild(link);
    } catch (e) {}
  }

I was able to successfully test this function with the following specification.

  it('should create link tag', () => {
    seoLinkService.createLinkForCanonicalURL({rel: 'canonical', href: 'www.example.org'});
    expect(document.querySelector("link").getAttribute('rel')).toEqual('canonical');
    expect(document.querySelector("link").getAttribute('href')).toEqual('www.example.org');
  });

Now I am attempting to test scenarios where errors occur.

Below is the updated spec,

  it('should not create link tag', () => {
    seoLinkService.createLinkForCanonicalURL(undefined);
    expect(document.querySelector("link").getAttribute('rel')).toBeFalsy();
  });

When running the above code, my specifications failed with the following error message.

Expected 'canonical' to be falsy.

Can anyone provide guidance on how to effectively test error scenarios? Your assistance would be greatly appreciated.

Answer №1

To properly prepare for the upcoming tests, it is important to remove the previously created link tag in the beforeEach function.

Here is an example of how this can be achieved:

describe('test', () => {

  ...

  beforeEach(() => {
    document.querySelectorAll("link").forEach(e => e.remove());
  })


  it('should create link tag', () => {
    seoLinkService.createLinkForCanonicalURL({rel: 'canonical', href: 'www.example.org'});
    expect(document.querySelector("link").getAttribute('rel')).toEqual('canonical');
    expect(document.querySelector("link").getAttribute('href')).toEqual('www.example.org');
  });

  it('should not create link tag', () => {
    seoLinkService.createLinkForCanonicalURL(undefined);
    expect(document.querySelector("link").getAttribute('rel')).toBeFalsy();
  });
})

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

Unable to locate properties "offsetHeight" or "clientHeight" within a React/Next.js project developed in TypeScript

I have a unique customized collapsible FAQ feature that adjusts its height based on whether it's expanded or collapsed. import { useState, useRef, useEffect } from "react"; export default FAQItem({title, description}: FAQItemProps) { cons ...

How can I choose an option in a dropdown field labeled as ejs-dropdownlist with WebDriver in an Angular web application?

After spending some time grappling with this issue, I managed to find a solution. The ejs-dropdownlist tag is present on a web page that is currently in the development stage using Angular. Here is the complete XPath for the dropdown I am attempting to i ...

How can I display the values stored in an array of objects in Angular 2

I need help printing out the value of id from an array that is structured like this: locations = [ {id: '1', lat: 51.5239935252832, lng: 5.137663903579778, content: 'Kids Jungalow (5p)'}, {id: '2', lat: 51.523 ...

What is the method for identifying if an ion-content element contains a scrollbar?

Is it possible to dynamically show or hide elements based on the presence of a scrollbar within ion-content? Specifically, I want to display a button for loading more items in a list when there is no scrollbar, and hide it when a scrollbar is present (thus ...

The CORS Policy has prevented Angular from accessing the header, as the request header field for authentication is restricted

After reviewing a multitude of similar questions regarding CORS and headers, I have attempted various solutions but I am still encountering this error specifically in Google Chrome. Access to XMLHttpRequest at 'https://service.domain.com/clientlist&ap ...

Troubles in transitioning a local project from Angular 2 to Angular 4 using Angular-cli

I have been working on updating an angular-cli/angular 2 project to Angular 4. I successfully updated the package.json file with all the necessary Angular 4 modules, but encountered an issue when running the application. Upon running the app, I received th ...

"Utilizing the Power of Typescript with Koa-Router and Passport for a

As a beginner in Typescript, I am facing challenges while trying to integrate koa-router and koa-passport. I have installed all the necessary @types\ packages. import Koa from "koa"; import Route from "koa-router"; import passport from "koa-passport" ...

Retrieve an established SQS eventSource in AWS CDK

When working with AWS CDK, there is a built-in function called addEventSource that allows you to easily add new SQS triggers (eventSources) to a lambda function. However, I'm curious if there is a way to access and modify the existing eventSources ass ...

Is it just me, or does the this.router.subscribe method no longer exist in Angular 2's @angular/router library?

I'm experiencing an issue in Angular 2 with the library @angular/router. It appears that the method this.router.subscribe no longer exists. Previously, this code worked fine on an older version of the router that has since been deprecated. Does anyon ...

Converting JavaScript object data to x-www-form-urlencoded: A step-by-step guide

I am trying to convert a JavaScript object into x-www-form-urlencoded. Is there a way to achieve this using Angular 2? export class Compentency { competencies : number[]; } postData() { let array = [1, 2, 3]; this.comp.competencies ...

Setting a specific time zone as the default in Flatpickr, rather than relying on the system's time zone, can be

Flatpickr relies on the Date object internally, which defaults to using the local time of the computer. I am currently using Flatpickr version 4.6.6 Is there a method to specify a specific time zone for flatpickr? ...

Is there a way to customize the appearance of a MUI5 Tooltip using emotion?

I went through the information in this Stack Overflow post and experimented with the styled method. The code snippet I used is as follows: import * as React from 'react'; import { styled } from '@mui/material/styles'; import Tooltip, { ...

How can you effectively declare a computed getter in MobX that aggregates an observable list?

Within my project, I have a class hierarchy consisting of projects, task lists, and tasks. Each array is marked as @observable. Now, I am looking to create a "@computed get allTasks" function within the project class that aggregates all tasks from all task ...

Nativescript encountered an issue while attempting to generate the application. The module failed to load: app/main.js

I'm currently experimenting with the sample-Groceries application, and after installing NativeScript and angular 2 on two different machines, I encountered the same error message when trying to execute: tns run android --emulator While IOS operations ...

Is there a way to dynamically adjust the size of an image in NodeJS utilizing Sharp, when only provided with a URL, employing async/await, and ensuring no local duplicate is

In my current work environment, the only image processing library available is NodeJS's Sharp for scaling images. It has been reliable due to its pipe-based nature, but now I have been given the task of converting it to TypeScript and utilizing Async/ ...

To avoid TS2556 error in TypeScript, make sure that a spread argument is either in a tuple type or is passed to a rest parameter, especially when using

So I'm working with this function: export default function getObjectFromTwoArrays(keyArr: Array<any>, valueArr: Array<any>) { // Beginning point: // [key1,key2,key3], // [value1,value2,value3] // // End point: { // key1: val ...

Generate TypeScript type definitions for environment variables in my configuration file using code

Imagine I have a configuration file named .env.local: SOME_VAR="this is very secret" SOME_OTHER_VAR="this is not so secret, but needs to be different during tests" Is there a way to create a TypeScript type based on the keys in this fi ...

Is there a way to utilize "npm install ts-node-dev -D" in Termux?

npm ERR! code EACCES npm ERR! syscall symlink npm ERR! path ../acorn/bin/acorn npm ERR! dest /storage/emulated/0/bot-baiano/node_modules/.bin/acorn npm ERR! errno -13 npm ERR! Error: EACCES: permission denied, unable to create symlink fro ...

Generating dynamic components in Angular relies on a string input

Imagine I have an API that provides me with the following data: { title: 'title1', type: 'FullComponent' }, { title: 'title2', type: 'HalfComponent' }, { title: 'title3', type: 'Half ...

Conditional Rendering with Next.js for Smaller Displays

I've implemented a custom hook to dynamically render different elements on the webpage depending on the screen size. However, I've noticed that there is a slight delay during rendering due to the useEffect hook. The conditionally rendered element ...