I am totally new to Jasmine and trying to learn how to write Unit tests for my components in Angular 4. I am adding a class to the classList of the button on ngOnInit() of the Component. Now when I try to run the test, it says, cannot find property 'classList' of null. This is what I have tried so far.
Component.ts
ngOnInit() {
document.querySelector('.button-visible').classList.add('hidden');
}
This is what im trying to do in my spec ts file.
Component.spec.ts
describe('AppComponent', () => {
let component = AppComponent;
let fixture: ComponentFixture<AppComponent>;
let compiledElement;
});
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AppComponent]
.....
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
compiledElement = fixture.debugElement.nativeElement;
fixture.detectChanges();
});
it('should create component', () => {
expect(compiledElement.querySelector('button.button-visible').classList).toContain('hidden');
expect(component).toBeTruthy();
});
});
I am not able to figure out how to test. Any help is appreciated.
In order to run tests when you have a component that needs to look for things outside of it, you'll need to create a test harness that uses your component and has all of the needed items. In your case, you'll need a test component that contains a DOM node that has the button-visible class applied.
You can create a test component right in your test spec to use:
@Component({
template: `
<button class="button-visible">Test Button</button>
<app-component></app-component>
`,
})
class TestHostComponent {
}
You'll then need to change your test setup to include and use this new component:
describe('AppComponent', () => {
let fixture: ComponentFixture<TestHostComponent>;
let testHostComponent: TestHostComponent;
let component: AppComponent;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AppComponent, TestHostComponent]
.....
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestHostComponent);
testHostComponent = fixture.componentInstance;
component = fixture.debugElement.query(By.directive(AppComponent)).componentInstance;
fixture.detectChanges();
});
});
You can then run your test to see if the button in your test component has the class applied:
it('should add "hidden" class to HTML elements with "button-visible" class', () => {
const buttonElement = fixture.debugElement.query(By.css('.button-visible.hidden'));
expect(buttonElement).toBeTruthy();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With