1

I got below error while writing the unit test in Angular using Jest. I have gone through all the similar suggestions here in stackoverflow, but none were helpful.

Error: unsafe value used in a resource URL context (see https://g.co/ng/security#xss) Jest

Below is the code from test file for your review.

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';

import { MaterialModule } from '../../Material/material.module';

import { DashboardViewComponent } from './dashboard-view.component';

describe('DashboardViewComponent', () => {
  let component: DashboardViewComponent;
  let fixture: ComponentFixture<DashboardViewComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [
        RouterTestingModule, 
        HttpClientTestingModule,
        MaterialModule,
      ],
      declarations: [ DashboardViewComponent ],
      providers: [{
        provide: DomSanitizer,
        useValue: {
          bypassSecurityTrustResourceUrl: (): SafeResourceUrl => ''
        }
      }],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(DashboardViewComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  test('should create', () => {
    // expect(component).toMatchSnapshot();
    expect(component).toBeTruthy();
  });
});

Thanks in advance.

3
  • Can you try not mocking DomSanitizer to see if the issue goes away? Or try mocking it like so: stackoverflow.com/a/51894364/7365461. Commented Apr 18, 2022 at 13:02
  • If somehow you managed to fix this, could you post the answer please ? This bug hurt my *** for 4 hours now.. Commented Jun 16, 2022 at 12:19
  • I created a pipe for DomSanitizer and it made the magic. Commented Aug 2, 2022 at 7:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.