angulartypescriptjestjsangular2-services

How to test component that use URL api using Jest in angular


I am have a case where my code is using the URL api, created as such:

 let url = new URL('...');
 url.searchParams.set('action', action);

How ever while writing unit test it fails and the Error is:

 TypeError: Invalid URL: service

So far what i tried:

let mockUrl:URL;
describe('MyService', () => {
  beforeEach(() => {
    mockUrl = new URL(dummyUrl);
    TestBed.configureTestingModule({
      providers: [{provide:URL, useValue:mockUrl}]
    });
  });

Error remains the same


Solution

  • It is not the URL object that you need to provide in the providers array, basically Jest understand URL by default, they issue is URL object receives invalid URL thus it throws TypeError: Invalid URL

    let url = new URL(undefined); //or invalid Url