我正在努力模拟 Angular 中的绝对路径。
it('should return current URL when no URL provided and og:url meta tag does not exist', () => {
const currentUrl: string = 'https://example.com/current';
const documentSpy = jasmine.createSpyObj('document', ['location']);
documentSpy.location.and.returnValue({ href: currentUrl });
TestBed.configureTestingModule({
providers: [
ShareService,
{ provide: DOCUMENT, useValue: documentSpy }
]
});
service = TestBed.inject(ShareService);
expect((service as any).getComputedUrl('')).toEqual(currentUrl);
});
此代码的问题是它替换了文档对象,删除了像
querySelector
这样的函数,这导致测试失败
是否有一个角度服务返回我可以用来模拟的绝对路径?
我认为你应该使用
spyOnProperty
。
spyOnProperty(document, 'location', 'get').and.returnValue({ href: currentUrl })