Angular is always updating and bringing new features. Angular CLI has also been updated (currently at version 6.x). With latest version it also updated few parameters when running tests.
Running tests
To run tests, we can execute ng test or npm test. This opens the browser and watches for changes. If we change the file, it reruns the tests. This is great for development, but it won’t work on our CI. We have to add few commands:
–watch=false
This will run tests only once and exit. This is replacement for –single-run which was used in older versions.
–no-progress
This is useful to add when running on CI just to limit among of logs.
–browsers=Chrome
We can specify the browser we want to run. This is replacement for –browser which again was working with older versions.
Browsers
By default, tests will be run with Chrome. To be able to better run on CI, we must enable sandbox. We can also run headless chrome. To enable this, we add
1 2 3 4 5 6 7 8 9 10 |
customLaunchers: { ChromeNoSandbox: { base: 'Chrome', flags: ['--no-sandbox'] }, ChromeNoSandboxHeadless: { base: 'ChromeHeadless', flags: ['--no-sandbox'] } }, |
in file karma.conf.js below browsers value.
Now we can run tests as
1 |
$ ng test --watch=false --no-progress --browsers=ChromeNoSandbox |
or to run headless Chrome
1 |
$ ng test --watch=false --no-progress --browsers=ChromeNoSandboxHeadless |
You can also update package.json and add additional script
1 2 3 4 5 6 7 |
"scripts": { ... "test": "ng test", "test:prod": "ng test --watch=false --no-progress --browsers=ChromeNoSandbox", "test:prod-headless": "ng test --watch=false --no-progress --browsers=ChromeNoSandboxHeadless", ... } |
and then run the test as
1 |
$ npm run test:prod |
CI
I’m using Circle CI for building. Now we can update the configuration to run tests
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
version: 2 jobs: build: docker: - image: circleci/node:8.9-browsers working_directory: ~/repos steps: - checkout - restore_cache: keys: - v1-dependencies-{{ checksum "package.json" }} - v1-dependencies- - run: npm run install - save_cache: paths: - node_modules key: v1-dependencies-{{ checksum "package.json" }} - run: npm run test:prod-headless - run: npm run build:prod |
This will run our headless Chrome. If we want to run normal Chrome, then we must update run command.
1 |
- run: xvfb-run -a npm run test:prod |
xvfb-run is used to run npm run command using a virtual screen, which is needed by Chrome.