Search code examples
angularjasmine

Angular unit test case for this.document.body.setAttribute()


document.body.setAttribute('data', 'data1') inside ngOnInint() in my component.

How can I write the unit test for this line?


Solution

  • You can create a unit test using Jasmine and TestBed in the following way:

    import { ComponentFixture, TestBed } from '@angular/core/testing';
    import { YourComponent } from './your-component.component';
    
    describe('YourComponent', () => {
      let fixture: ComponentFixture<YourComponent>;
    
      beforeEach(async () => {
        await TestBed.configureTestingModule({
          declarations: [YourComponent],
        }).compileComponents();
      });
    
      beforeEach(() => {
        fixture = TestBed.createComponent(YourComponent);
      });
    
      it('should set data attribute on document body in ngOnInit', () => {
        const spy = spyOn(document.body, 'setAttribute');
        fixture.detectChanges();
        expect(spy).toHaveBeenCalledWith('data', 'data1');
      });
    });