我创建了一个服务来添加canonical
标签。
以下是服务代码,
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) {}
}
我可以成功地将此功能与以下规范结合在一起。
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();
});
使用上面的代码,我的规范失败并显示以下消息。
预计"规范"是虚假的。
如何测试错误方案。请帮忙。
您需要在beforeEach
中删除之前创建的链接标记。
喜欢这个:
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();
});
})