我正在尝试测试使用window.location
的三元分支。
@Injectable()
export class ABCService {
private hostUrl = (window.location.host.indexOf('localhost') > -1) ? 'example.com' : window.location.host;
...
测试柜:
it('check alternate URL', () => {
const URL = 'http://example.org/postMethod';
service.getData().subscribe(data => {
expect(data.length).toBe(1);
});
const req = httpMock.expectOne(URL);
expect(req.request.url).toBe(URL);
req.flush({data:[1]});
});
获取错误:
Error: Expected one matching request for criteria "Match URL: http://example.org/postMethod", found none.
我如何测试window.location.host
是否不是本地主机的任何想法。尝试了(window as any).location = { ...window.location, host: 'http://example.org' };
仍然得到主机== localhost:9876;
或有什么办法可以覆盖模拟的window.location.host
值?
而不是引用全局变量,该变量可能无法根据您在哪个环境中(例如Angular Universal(来定义,而是使用依赖项注入。
在这种情况下,您可以从Angular的文档常数(https://angular.io/api/common/document(中获取所需的信息。
constructor(@Inject(DOCUMENT) private doc) {
console.log(this.doc.location.href);
}
在您的测试中,您可以对其进行模拟:
const service = new ABCService({location: {href: 'my-test-url'}} as any);
我需要更准确地了解您的问题和测试案例,请您提供stackblitz url吗?
无论如何,您可以使用Jasmine的spyOn
函数进行模拟窗口。Thyway,您可以提供模拟的功能及其返回值,而无需实际设置主机。
查看茉莉文档以获取更多信息。