代码之家  ›  专栏  ›  技术社区  ›  Ricardo Rocha

茉莉花+业力测试跑者:如何测试window.location.href

  •  0
  • Ricardo Rocha  · 技术社区  · 6 年前

    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");
        });
    });
    

    任何人都可以给一些提示我可以测试这个功能而不被重定向?

    3 回复  |  直到 6 年前
        1
  •  3
  •   mzoabi    6 年前

    你可以做一些简单的把戏:

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

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

        2
  •  1
  •   Damian Dziaduch    6 年前

    测试这一点的唯一方法是有能力设置 window 在里面 WindowService constructor 或通过 setter 伪造物品。你不能监视或修改 window.location ...