Suppose there are 2 components : AppComponent and TestComponent. I am calling TestComponent using it's directive in the HTML template of AppComponent. Now TestComponent has an @Input() property ( let it be myTitle ).
I am doing unit testing for TestComponent only. For title, i am passing a random value in the test itself. Here is the code for the same :
app.component.html
<span><app-test [myTitle]="title"></app-test></span>
app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent{
title = {name: 'hello-world'};
}
test.component.html
<p>test works!!{{myTitle.name}}</p>
test.component.ts
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit{
@Input() myTitle;
constructor(){
}
ngOnInit():void{
this.myTitle.name = "Hi!!";
}
}
test.component.spec.ts
describe('Test component',() =>{
let temp;
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(async(() =>{
TestBed.configureTestingModule({
declarations: [TestComponent],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(()=>{
temp = {name: "Heloooo"};
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
});
it('should check First',()=>{
component.myTitle = temp;
console.log(component.myTitle.name);
console.log(temp.name);
fixture.detectChanges();
console.log(component.myTitle.name);
console.log(temp.name);
expect(component.myTitle.name).toEqual(temp.name);
});
it('should check Second',()=>{
component.myTitle = temp;
console.log(component.myTitle.name);
console.log(temp.name);
fixture.detectChanges();
temp.name = "Majin Buu";
console.log(component.myTitle.name);
console.log(temp.name);
expect(component.myTitle.name).toEqual(temp.name);
});
});
Both the test passes and I don't know the reason why.
Questions:
Here suppose the input property is a simple string instead of an object, then the cases fail, which is what i was expecting. But for objects it is not working.
The console.log which i wrote gives the following output:
Test Case 1:
Heloooo
Heloooo
Hi!!
Hi!!
Test Case 2:
Heloooo
Heloooo
Majin Buu
Majin Buu
How come it is showing latest value for object.name? I thought that the object
temp
is local to this scenario.
- Does fixture.detectChanges() only calls ngOnInit? If no, then how does it work? And how to make sure that the test cases fail for objects too?
I am new to this community, so please help me improve the question if there are any fails.