Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
912 views
in Technique[技术] by (71.8m points)

testing - Cant use base class for integration tests in Angular

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...