【问题标题】:jasmine + karma test runner: how to test window.location.hrefjasmine + karma 测试运行器:如何测试 window.location.href
【发布时间】:2019-02-17 00:35:06
【问题描述】:

我有一个服务可以封装window 对象的使用:

@Injectable()
export class WindowService {
    constructor(){};
    get window() : Window {
        return window;
    }
    get href(): string {
        return window.location.href;
    }
    set href(url: string) {
        window.location.href = url;
    }
}

然后我有以下茉莉花测试:

describe('WindowService Test Suite', () => {
    let windowService: WindowService;

    beforeEach(() => { 
        windowService = new WindowService();
    });

    it('should set the href', () => {
        windowService.href = "/test";
        expect(windowService.href).toBe("/test");
    });
});

问题是当我设置href时,业力重定向到那个url并导致其他测试没有运行。

任何人都可以提供一些提示,我可以在不被重定向的情况下测试此功能?

【问题讨论】:

    标签: angular typescript jasmine karma-jasmine karma-runner


    【解决方案1】:

    你可以做简单的把戏:

    it('should set the href', () => {
        var currentUrl = windowService.href;
        windowService.href = "#test";
        expect(windowService.href).toBe(currentUrl + "#test");
    });
    

    #test 不会重定向您的页面,但会搜索 id=test 的 DIV 以滚动到该页面。

    【讨论】:

      【解决方案2】:

      对此进行测试的唯一方法是能够通过constructorsetterWindowService 中的window 设置为假对象。你不能窥探或修改window.location...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-04
        • 1970-01-01
        • 1970-01-01
        • 2016-10-06
        • 2016-12-18
        • 2020-08-26
        • 2015-12-07
        • 1970-01-01
        相关资源
        最近更新 更多