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.

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

0 Answers0