【问题标题】:Angular Unit test with Jasmine to test on location.href使用 Jasmine 进行 Angular 单元测试以测试 location.href
【发布时间】:2023-01-13 22:07:47
【问题描述】:

我有一个在 url 中查找位置的函数,如果找到,该函数将删除它并更新 location.href。如何编写测试?

export class Auth0IdentityService extends IdentityService {
    constructor() {}

    removePlaces(): void {
        const url = new URL(window.location.href)
        if ((url.searchParams.get("place")) {
            url.searchParams.delete("place");
        window.location.href = url.href;
        }
    }
}

`

我的 it 块是:

it('should remove place from url', async () => {
    const spy = spyOnProperty(window.location, 'href', 'get').and.returnValue("http://localhost:3000/?place=xxxx");
    component.removePlaces()
    expect (window.location.href).toBe ("http://localhost:3000/?place=xxxx")
})

`

它以错误消息“href 未声明为可配置”结束。

【问题讨论】:

    标签: angular unit-testing jasmine spy


    【解决方案1】:

    您必须执行类似的操作才能将 Window 对象注入构造函数。在构造函数中注入 Window 对象使单元测试更加容易:https://stackoverflow.com/a/40292188/7365461

    按照 AppModule@NgModule 中显示的答案进行操作。

    然后对您的服务进行以下更改:

    export class Auth0IdentityService extends IdentityService {
        // Get a handle on the Window object
        constructor( @Inject('Window') private window: Window) { }
    
        removePlaces(): void {
            // refer to it as this.window
            const url = new URL(this.window.location.href)
            if ((url.searchParams.get("place")) {
                url.searchParams.delete("place");
            this.window.location.href = url.href;
            }
        }
    }
    

    然后在你的测试中模拟窗口

    let mockWindow: any;
    ....
    
    // mock the window however you wish
    mockWindow = { location: { href:: 'http://localhost:3000/?place=xxxx' } };
    TestBed.configureTestingModule({
      ...,
      providers: [
        ....
        // Provide the mock for the real window
        { provide: 'Window', useValue: mockWindow }
        ....
      ],
      ...
    });
    

    然后尝试测试:

    it('should remove place from url', async () => {
        component.removePlaces()
    
        expect (mockWindow.location.href).toBe("http://localhost:3000/?place=xxxx")
    })
    

    【讨论】:

      猜你喜欢
      • 2016-08-14
      • 1970-01-01
      • 1970-01-01
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多