I have a component "AuthorComponent" with a register form and a AuthorService. In that component I'm using reactive forms. So, I want to make integration test that asserts that GIVEN completed form, WHEN click on submit button, THEN AuthorService calls #save().
The setup for this test is:
beforeEach(fakeAsync(()=>{
TestBed.configureTestingModule({
declarations:[AuthorComponent],
imports:[
ReactiveFormModule
],
providers:[
{provide:AuthorService, useValue:{save(){}}}
]
}).compileComponents()
fixture=TestBed.createComponent(AuthorComponent)
fakeService=TestBed.inject(AuthorService)
}
Trying keep test code clean, I created a class that wrap the ComponentFixture and give methods that make actions in component template.
class AuthorWrapper{
fix:ComponentFixture<AuthorComponent>
constructor(fixx: ComponentFixture<AuthorComponent>){
this.fix=fixx
}
setInputValue(newValue: string){
let inputElement=this.fix.debugElement.query(By.css('inputReference')).nativeElement
inputElement.value=newValue
inputElement.dispatchEvent(new Event('input'))
this.fix.detectChanges()
}
clickSubmitFormButton(){
let inputElement=this.fix.debugElement.query(By.css('buttonReference')).nativeElement
inputElement.click()
this.fix.detectChanges()
}
}
So, when I make a test that like this, the test pass:
it('service should call #save,()=>{
let element=fixture.debugElement.query(By.css('inputReference')).nativeElement
element.value='newValue'
authorWrapper.clickSubmitFormButton()
expect(fakeService.save).toHaveBeenCalled()
But then, when I try use #setInputValue from authorWrapper to set form value, then the template receive the new value, but the form don't update value and then fakeService is not called. This behavior is like the ReactiveFormModule is not working in the component of the ComponentFixture inside AuthorWrapper. On the other hand, it don't make sense because its was passed as reference in AuthorWrapper constructor, so the ComponentFixture and its componentInstance should be the same for in and out AuthorWrapper.
Does someone know what is happening?
question from:
https://stackoverflow.com/questions/65830417/cant-use-base-class-for-integration-tests-in-angular 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…