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.