Testing the component

Now that we have our component created, we need to test it. To do this, we rely on the done callback passed to the test function to notify Jasmine that the test is done. If we don't specify the done parameter, our test won't be executed because we execute our assertions in a promise and if we don't call it, we will get a timeout error since Jasmine won't be able to know when our test completed. Let's apply the following changes to the info-box.spec.js file:

 import {StageComponent} from 'aurelia-testing';
import {bootstrap} from 'aurelia-bootstrapper';

describe('Info-Box', () => {

it('should render the username and topic', done => {
let component = StageComponent
.withResources('info-box')
.inView('<info-box></info-box>');

component
.create(bootstrap)
.then(() => {

const h1 = component.element.querySelector('h1').innerHTML;
const pa = component.element.querySelector('p').innerHTML;

expect(h1).toBe('Hello, Reader!');
expect(pa).toBe('You are learning: <b>Testing and Debugging </b>');

done();


})
.catch(e => console.log(e.toString()));
});
});
You should be aware that if you are using Webpack, you might need to import PLATFORM from the aurelia-pal module in order to load the info-box resource as follows—.withResourceS(PLATFORM.moduleName('info-box')). For additional Webpack considerations, visit the official site at https://aurelia.io/docs/build-systems/webpack.

In the then function, we pass our callback that will use the component.element.querySelector function to access the HTML elements into the info-box component, and we use the innerHTML property of the elements to access the element's values.

Next, we compare the values of the elements by the expected values and when all the expect statements are executed, we call the done() function to tell Jasmine we have finished this test case.

Lastly, a catch callback is passed to print any error detected in the test process. Once everything is complete, run the following command in your Terminal:

$ au karma

If everything went right, the Chrome web browser should be opened and you should see the following output in your Terminal window:

...
Starting 'karma'...
...
Chrome 62.0.3202 (Mac OS X 10.12.6): Executed 1 of 1 SUCCESS (0 secs / 0.105 secChrome 62.0.3202 (Mac OS X 10.12.6): Executed 1 of 1 SUCCESS (0.109 secs / 0.105 secs)
Finished 'karma'

That's it! Now you know how to test Aurelia components. A little challenge for you is to apply everything learned in a TDD cycle. Have fun!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset