简体   繁体   English

Angular 使用 Jasmine 进行单元测试以在 location.href 上进行测试

[英]Angular Unit test with Jasmine to test on location.href

I have a function which looks for place in the url and if found, the function will remove it and update location.href.我有一个 function,它在 url 中寻找位置,如果找到,function 将删除它并更新 location.href。 How to write a test?如何编写测试?

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

` `

My it block is:我的 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")
})

` `

It end up with error message "href is not declared configurable".它以错误消息“href 未声明为可配置”结束。

You have to do something like this to be able to inject the Window object into the constructor.你必须做这样的事情才能将 Window object 注入到构造函数中。 Injecting the Window object in the constructor makes unit testing much easier: https://stackoverflow.com/a/40292188/7365461 .在构造函数中注入 Window object 使单元测试更加容易: https://stackoverflow.com/a/40292188/7365461

Do what the answer shows in the @NgModule in the AppModule .执行 AppModule 中@NgModule中显示的AppModule

Then make the following changes to your service:然后对您的服务进行以下更改:

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

And then mock the window in your test然后在你的测试中模拟 window

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 }
    ....
  ],
  ...
});

And then try to test:然后尝试测试:

it('should remove place from url', async () => {
    component.removePlaces()

    expect (mockWindow.location.href).toBe("http://localhost:3000/?place=xxxx")
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM