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

1.6k Views Asked by At

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

1

There are 1 best solutions below

0
Muhammad Rehan On BEST ANSWER

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