The componentTestingSetup is used to set up the component driver. Create a function that returns the result of the componentTestingSetup by passing at least your component class and the driver associated to the component :
functiontestingSetup(){
returncomponentTestingSetup({
componentClass:MyComponent,
driver:MyComponentDriver
})
}
Other optional parameters can be defined in the conf passed to this method :
{
componentClass: any
driver: any
servicesToStub?:any[]
declarations?:any[]
providers?:any[]
overrideProviders?:any[]
imports?:any[]
}
servicesToSub (optional) refers to the services that need a mock by creating a Spy. It uses the jasmine-auto-spies package under the hood.
overrideProviders (optional) refers to the component provided services that need a mock by creating a Spy.
declarations, providers, imports are optionals and are used in the same way that if you declare the TestBed configurations (because it uses the TestBed behind the scenes)
3 - get your component driver
Get your component driver by calling the componentTestingSetup method returned by componentTestingSetup
the componentTestingSetup method sets up the TestBed under the hood. You still can access it if needed like this :
componentDriver.TestBed
Example
In this example, we use the jasmine-given library to write our test suite with Given, When, Then functions.
Given : describe the input
When : describe the action
Then : describe the output
You can use one of my other packages angular-karma-gwt to setup everything you need to use jasmine-given and some other cool stuff. A simple ng add angular-karma-gwt will download the packages and set up everything you need automatically.
Our app
Let's assume that our app is composed by :
a question component
a service component
a component provided service
an answer directive binded to our element that display the answers
<div *ngFor="let answer of questionData.answers" [answerDirective]="answer">{{ answer }}</div>
<button>Previous</button>
<button>Next</button>
`,
providers:[LoggerService]
})
classQuestionComponent{
questionData:QuestionData
constructor(questionService:QuestionService){
questionService
.getQuestion()
.pipe(first())
.subscribe(question=>{
logger.log(question)
this.questionData=question
})
}
}
@Injectable()
classQuestionService{
@AsyncSpyable()// => Decorator from the jasmine-auto-spies package
getQuestion():Observable<QuestionData>{
returnof(null)
}
}
@Injectable()
exportclassLoggerService{
log(data):void{
console.log(data)
}
}
@Directive({
selector:'[answerDirective]'
})
classAnswerDirective{
@Input('answerDirective')answer:string
}
1 - Create your component driver class
This class can be empty and only extend the ComponentDriver class. But here, we added some methods to query some elements (DOM and directives) of our component to test the UI.
You can query child component in the same way you query directives (components are directives).