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
- Install
npm install --save-dev mocha chai \ ts-node typescript \ @types/chai @types/mocha
- Update
package.json
"scripts": { "unit": "cross-env TS_NODE_COMPILER_OPTIONS='{ \"module\": \"commonjs\" }' mocha --require ts-node/register test/**/*.ts" }
- 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'); }); });
- Run it:
npm run unit
Research
- Unit testing node applications with TypeScript — using mocha and chai
- Running unit tests selectively with Angular7
Written with StackEdit.