Problem Statement

Component testing runs via ng test and there is no way to specify the specific test you are interested in. This means wasting time sorting out and fixing generated specs that are failing because they don’t recognize your component selectors.

  • Component tests are unit tests by nature so they can’t be run via protractor.
  • JEST may be a viable alternative.

Or you can be clever and move the code, which you want to test, into utility classes. Then run mocha with support for typescript compilation!

Solution

  1. Install
     npm install --save-dev mocha chai \
       ts-node typescript \
       @types/chai @types/mocha
    
  2. Update package.json
     "scripts": {
       "unit": "cross-env TS_NODE_COMPILER_OPTIONS='{ \"module\": \"commonjs\" }' mocha --require ts-node/register test/**/*.ts"
     }
    
  3. Create test/test.ts
     import { describe } from 'mocha';
     import * as moment from 'moment';
     import * as chai from 'chai';
     var  expect  =  chai.expect;
    
     import { MyComponent } from './../src/app/my/my.component';
    
     describe('describe-block', () => {
       it('it-block', () => {
         expect(true).to.equal(true);
    
         let myComponent = new MyComponent();
         expect(myComponent.sayBlue()).to.equal('blue');
       });
     });
    
  4. Run it: npm run unit

Research

Written with StackEdit.