[英]Angular: Unit Testing - Not able to test Ternary branch for code coverage
我正在嘗試測試使用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
是否不是localhost的任何想法。 嘗試過(window as any).location = { ...window.location, host: 'http://example.org' };
仍在獲取主機== localhost:9876;
或有什么方法可以覆蓋模擬它的window.location.host
值?
可以使用依賴項注入來代替引用可能根據您在其中運行應用程序的環境而未定義的全局變量(例如Angular Universal)。
在這種情況下,您可以從Angular的DOCUMENT常量( 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網址嗎?
無論如何,您可以使用茉莉花的spyOn
函數來模擬window.location。 這樣,您可以提供模擬它的功能及其返回值,而無需實際設置主機。
請參閱Jasmine文檔以獲取更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.