Reputation: 3566
According to the Angular2 testing documentation, for testing components we should create an object like this:
component = fixture.createInstance;
but for isolates unit testing, like for service, it is said to create an instance like this:
component = new componentClass(); //traditional way of creating objects by calling class constructor
I'm not very much clear about what exactly is the difference between these two approaches for creating instances. Also, I've noticed accessibility difference using both of these. Does anybody has a clear idea about the difference between these two?
Upvotes: 1
Views: 430
Reputation: 209012
Isolated tests are for when you only want to test the internal behavior of the class. For instance
class MyComponent {
doSomething(): string {}
}
let component = new MyComponent();
expect(component.doSomething()).toBe('Hello World');
Here you're only going to test the behavior of the doSomething
method. That's it.
With the isolated tests you can't test the DOM interaction, as the template is never compiled. For this we should let Angular create the component. Then the component will go through through the actual lifecycle it would go through as it it was in the real application
@Component({
template: `<h1>{{ message }}</h1>
})
class MyComponent {
message = 'Hello World'
}
let fixture = TestBed.createComponent(MyComponent);
fixture.component.message = 'new message';
fixture.detectedChanges();
expect(fixture.debugElement.query(By.css('h1')).nativeElement.textContent)
.toBe('new message');
You couldn't do this in an isolated test.
Upvotes: 2