If we have 2 components, namely AppComponent and TestComponent. The TestComponent is being called using its directive in the HTML template of the AppComponent. Within the TestComponent, there is an @Input() property named myTitle.
Unit testing is being performed solely on the TestComponent. A random value is passed for the title within the test. Below is the code snippet:
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>
<button (click)="onClick()">Click Please !!!</button>
test.component.ts
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit{
@Input() myTitle;
filter;
constructor(){
}
ngOnInit():void{
this.myTitle.name = "Hi!!";
}
onClick(){
this.filter="GokuSSj3";
}
}
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 whether onClick is called on button click or not and also the value of filter',()=>{
component.myTitle = temp;
spyOn(component,'onClick');
fixture.detectChanges();
let btn = fixture.debugElement.query(By.css('button'));
btn.triggerEventHandler('click',null);
fixture.whenStable().then(()=>{
expect(component.onClick).toHaveBeenCalled();
expect(component.filter).toEqual("GokuSSj3");
});
});
The second test case indicates an error: Expected undefined to equal 'GokuSSj3'. Why does this happen despite onClick being triggered?
Feedback from experienced community members on how to enhance the question is greatly appreciated as I am new here!