Я пытаюсь создать несколько юнит-тестов для моего seoService
, но я не знаю, как я должен высмеивать канонические и альтернативные ссылки и определять, были ли они созданы в голове.
Seo.service.ts
import { DOCUMENT } from "@angular/common";
import { Injectable, Inject } from "@angular/core";
@Injectable()
export class SeoService {
config = {
languages: ["en", "fi", "nb", "sv", "ja", "de"]
};
constructor(@Inject(DOCUMENT) private document: Document) {}
initialize() {
this.removeLinkForHreflangs();
this.createLinkForHreflangs();
}
private createLinkForHreflangs() {
let pathName = this.document.location.pathname;
const routeLanguage = pathName.substring(1, 3);
if (this.config.languages.includes(routeLanguage)) {
pathName = pathName.substring(3);
}
this.config.languages.map((language, index) => {
const link: HTMLLinkElement = this.document.createElement("link");
if (index === 0) {
link.setAttribute("rel", "canonical");
} else {
link.setAttribute("rel", "alternate");
link.setAttribute("hreflang", language);
}
link.setAttribute(
"href",
`${this.document.location.origin}/${language}${pathName}`
);
this.document.head.appendChild(link);
});
const linkDefault: HTMLLinkElement = this.document.createElement("link");
linkDefault.setAttribute("rel", "alternate");
linkDefault.setAttribute("hreflang", "x-default");
linkDefault.setAttribute(
"href",
`${this.document.location.origin}/${this.config.languages[0]}${pathName}`
);
this.document.head.appendChild(linkDefault);
}
private removeLinkForHreflangs() {
const canonical = this.document.querySelector(`link[rel='canonical']`);
const alternate = this.document.querySelectorAll(`link[rel='alternate']`);
if (canonical && alternate) {
this.document.head.removeChild(canonical);
alternate.forEach(element => {
element.remove();
});
}
}
}
Seo.service.spec.ts
import { TestBed, inject } from '@angular/core/testing';
import { Subject } from 'rxjs';
import { SeoService } from './seo.service';
describe('SeoService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
SeoService,
],
});
});
describe('.initialize()', () => {
it('should add canonical and alternate links to the head',
inject(SeoService, (service: SeoService) => {
service.initialize();
}));
it('should update canonical and alternate links to the head',
inject(SeoService, (service: SeoService) => {
service.initialize();
}));
});
});
И я инициализировал службу в app.componentЯ новичок в модульном тестировании, и я пытаюсь понять, нужны ли эти тесты, а также какие другие тесты я должен написать, чтобы охватить условия метода.
Также ссылка доступна на https://stackblitz.com/edit/angular-qmx5rs