Generate Angular Unit Test Automatically

For those who are away from Test-Driven Development

Allen Kim
Digital-Heart

--

Photo by Alison Pang on Unsplash

How much do you like to write unit tests from the scratch? My guess is “not so much”. The reason behind this guess is that writing the first successful unit test is just a copy, paste, and modification job, and it’s not a pleasant task.

What if there is a command that can do this job (copy, paste, and modification)?

TL;DR; Yes, there is a command.

Assuming you coded your component, and you want to write a test,

$ npm install ngentest -g # to run this command anywhere
$ gentest my.component.ts # node_modules/.bin/gentest

This will output your auto-generated unit test, and it’s guaranteed to work.

Unit test requires more coding, and it’s true :(

Writing a component is one thing and testing it is another thing. To make your test work, you need to know code and test structure with the following;

  • Import statements
  • Classes to mock
  • Window objects to mock
  • Create TestBed and configure it before each test
  • Setup providers using mocks

--

--