this.document.body.setAttribute()的角度单元测试用例

问题描述 投票:0回答:1

document.body.setAttribute('data', 'data1')
在我的组件中的
ngOnInint()
内。

我该如何编写这一行的单元测试?

angular jasmine
1个回答
0
投票

您可以通过以下方式使用 Jasmine 和 TestBed 创建单元测试:

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');
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.