首页 > 解决方案 > 如何测试 locationStrategy.onPopState?

问题描述

我需要测试我的功能,但我遇到了困难。

我无法执行 100% 的覆盖,我的困难与通过函数 onPopState 调用的函数 history.pushState 有关。

有人能帮我吗?

    // This line is never being covered by my tests
    this.locationStrategy.onPopState(() => {
                history.pushState(null, null, url);
    });

我的服务代码:

    export class MyService {
        constructor(private readonly locationStrategy: LocationStrategy) { }
     
        blockNavigator(url: string) {
            history.pushState(null, null, urlAtual);
     
            // This line is never being covered by my tests
            this.locationStrategy.onPopState(() => {
                history.pushState(null, null, url);
            });
        }
    }

我的服务测试代码:

    describe('MyService ', () => {
        let myService: MyService;
        let locationStrategyMock: LocationStrategy;
    
    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
                BloqueioNavegacaoService,
                {
                    provide: LocationStrategy,
                    useValue: jasmine.createSpyObj('LocationStrategy', ['onPopState'])
                }
            ]
        });
    
        myService = getTestBed().inject(MyService);
        locationStrategyMock = getTestBed().inject(LocationStrategy);
    });
    
    
    describe('Methods:', () => {    
        it('.....', () => {
            spyOn(myService , 'blockNavigator').and.callThrough();
    
            locationStrategyMock.onPopState = jasmine.createSpy()
                .and.callFake(() => {
                    // window.history.pushState(null, null, 'url');
                });
    
            myService.blockNavigator(url);
    
            expect(myService.blockNavigator).toHaveBeenCalledTimes(1);
            expect(window.history.state).toBeNull();
            expect(window.history.length).toBeGreaterThanOrEqual(0);
        });
    });

标签: angularunit-testingjasmine

解决方案


我认为您可以利用.calls.mostRecent().args[0]获取函数参数的句柄并显式调用该函数然后断言。

看看下面,也有评论。

    describe('MyService ', () => {
        let myService: MyService;
        let locationStrategyMock: LocationStrategy;
        // Add this line
        let mockLocationStrategy: jasmine.SpyObj<LocationStrategy>;
    
    beforeEach(() => {
        // Add this line
        mockLocationStrategy = jasmine.createSpyObj('LocationStrategy', ['onPopState']);
        TestBed.configureTestingModule({
            providers: [
                BloqueioNavegacaoService,
                {
                    provide: LocationStrategy,
                    // change useValue here
                    useValue: mockLocationStrategy
                }
            ]
        });
    
        myService = getTestBed().inject(MyService);
        locationStrategyMock = getTestBed().inject(LocationStrategy);
    });
    
    
    describe('Methods:', () => {    
        it('.....', () => {
            // This line is not needed, we call it explicitly
            // spyOn(myService , 'blockNavigator').and.callThrough();
    
       
            myService.blockNavigator(url);
            // This line is not needed, we call it explicitly (asserting nothing)
            // expect(myService.blockNavigator).toHaveBeenCalledTimes(1);
            
           // get a handle of the function (first argument) of onPopState
           // when it is called (i.e. () => {
                // history.pushState(null, null, url);
           // }
            const callBackFunction = mockLocationStrategy.onPopState.calls.mostRecent().args[0];
            // Call the function
            callBackFunction();
            // Hopefully the bottom assertions work
            expect(window.history.state).toBeNull();
            expect(window.history.length).toBeGreaterThanOrEqual(0);
        });
    });

推荐阅读