I am unable to test getter and setter functions in Angular 5 using Karma. Any ideas as to where I'm going wrong?
The value is set and then the test waits a short duration for the setter function to resolve before calling the getter function. Here is the code:
service.ts
set header(h: string) {
this.zone.run(() => {
this._header = h;
});
}
get header(): string {
return this._header;
}
test.ts
before(() => {
service = new Service()
});
it('updates header', (done) => {
const header = 'test header';
service.header = header;
// Give header time to update
return Promise.delay(200)
.then(() => {
expect(service.header).to.equal(header);
})
});
I would expect the assertion to resolve successfully however I get an error
AssertionError: expected undefined to equal 'test header'
The tests are simple and pretty straightforward. We set the value of a specific attribute and then we check if the value we just set corresponds with the value of the getter. I hope you now have a clearer view of how you can test a Model’s getters and setters.
Sometimes, working on Angular components, you can discover using getters and setters could be very handy in achieving your goals. Especially when you are working on creating some UI library and even working on some business logic. What are getters and setters?
That’s true for every language, platform, or framework—Angular is not an exception. What makes things easier is that the Angular team thought about unit testing from the start, so the framework has built-in support for this type of testing.
Karma is the default test running for Angular. The AngularJs team created it after having difficulties testing Angular with the tools that existed at the time. Karma allows you to test your applications on real web browsers and real devices, such as tablets or phones. It’s also very flexible since it works with several testing frameworks.
Is there a reason that you wrap your set content into a zone ?
For 99% of all async activities i love the "fakeAsync" and the "tick" method of Angular.
it('should update header', fakeAsync( ()=>{
const header = 'test header';
service.header = header;
tick() // <= Will wait for for all microtransactions to finish
expect(service.header).to.equal(header);
}))
There are quite a few good articles about Macro- and Microtransactions in JavaScript. The short version is, that Promises and Subscriptions of an observable-emit are microtransactions.
"setTimeout" is an example for a macrotransaction.
The best about "tick()" in a fakeAsync-UnitTest is, that you dont have to make sugestions how long the code will need to wait. "tick()" just drains the microtransaction-queue so all waiting micro transactions will be resolved, before the test proceeds.
You can use them also when waiting for the changeDetection of Angular-components. :-)
I hope that helps a bit.
warm regards
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With