Testing

Any developer worth their salt should care about writing tests. Testing is not that hard to set up.

We need the following file to make testing work:

  • karma.conf.js: We are using karma as a test runner. This needs a config file that sets up where to find the tests, whether to run our tests in a headless browser or a real one, and lots of other things.

The noteworthy config needed in this file is:

        preprocessors: {
'./karma-test-shim.js': ['Webpack', 'sourcemap']
}

The preprocessing step is needed so that it compiles our TypeScript files into ES5 JavaScript. It will also set up proper source maps, as well as point out what files are needed from the Angular framework for our tests to run properly.

Another property worth mentioning is:

       var WebpackConfig = require('./webpack.test');
module.exports = function(config) {
var _config = {
Webpack : WebpackConfig
}

// other config omitted
config.set(_config);
}

This points to config specified in the Webpack.test.js  file.

  • webpack.test.js: This is just a copy of Webpack.common.js, normal config. However, by making it into a separate file, we have the ability to override certain configs later should we wish to.
  • karma-test-shim.js: This file, as mentioned before, is responsible for importing all parts of the Angular framework that are needed to run, core parts of the framework, as well as dedicated parts related to testing. The full file looks as follows:
        Error.stackTraceLimit = Infinity;

require('core-js/es6');
require('core-js/es7/reflect');
require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/proxy');
require('zone.js/dist/sync-test');
require('zone.js/dist/jasmine-patch');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');

var appContext = require.context('./src', true, /.spec.ts/);
appContext.keys().forEach(appContext);

var testing = require('@angular/core/testing');
var browser = require('@angular/platform-browser-dynamic/testing');

testing.TestBed.initTestEnvironment(
browser.BrowserDynamicTestingModule,
browser.platformBrowserDynamicTesting()
);

It is worth nothing the following line:

        var appContext = require.context('./scr, true, /.spec.ts/');

This defines what it looks for when trying to locate what tests to run. So, let's create a test that matches this pattern, test.spec.tsunder the src directory:

describe('should return true', () => {
it('true is true', () => expect(true).toBe(true) );
});

With all this set up correctly, you should be able to type:

npm run test

This should start up the Chrome browser. You should see the following:

Pressing the debug button will show the following screen, where it clearly indicates that it is running our test and the result, which is a passing test:

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

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