Run A Single Unit Test
OS?
Windows 8, Mac OSX El Capitan
Versions.
angular-cli: 1.0.0-beta.19-3 node: 6.3.0 os: win32 x64
Mention any other details that might be useful.
This is a feature request. The ability to run a single .spec.ts file would be excellent, when you guys get the chance. I recently switched from using Angular1 in Visual Studio where one could use the Test Explorer or the Chutzpah extension to run a test on a single component. Working on a large enterprise application, it's a huge pain to run the entire unit test suite (which takes a few minutes) every time I refactor a single component (and thus only need to run that component's tests).
A variation on the popular answer from @EugeneSnihovsky but this approach does not have the minimist dependency, better error handling if no spec file can be found and allows to run one or two or more tests:
(1) DO NOT ADD MINIMIST DEPENDECY (2) DO NOT MODIFY package.json (3)
Modify karma.conf.js. At top of file add:
const tags = process.argv.filter(arg => {
return (arg.endsWith('.component') || arg.endsWith('.service'))
})
and in config object in client field (that is also object) add field args:
client: {
args: [tags],
clearContext: false // leave Jasmine Spec Runner output visible in browser
}
(4)
Change code in src/test.ts to:
declare var __karma__: any
declare var require: any
const tags = __karma__.config.args[0]
// Prevent Karma from running prematurely.
__karma__.loaded = function () {}
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
)
let filterRegex
if (tags.length) {
const strTags = tags.join('|')
filterRegex = new RegExp(`(${strTags})\\.spec\\.ts$`) // SPECIFIC TEST SUITES AS PASSED TO ... npm test filter-list.component filter-list.service
} else {
filterRegex = /\.spec\.ts$/ // ALL TEST SUITES
}
// filterRegex = /(filter-list.component|filter-list.service)\.spec\.ts$/ // OR YOU CAN UNCOMMENT AND EDIT THIS LINE
const context = require.context('./', true, /\.spec\.ts$/)
const specFiles = context.keys().filter(path => filterRegex.test(path))
if (specFiles.length) {
specFiles.map(context)
__karma__.start()
} else {
console.warn(`Could not find any test suites for ${tags.join(', ')}`)
}
(5) Run your tests with ...
ng test (to test all) OR ng test your-cool.component your-cool.service OR npm test (to test all) OR npm test your-cool.component your-cool.service
@danday74 do you think it's possible to make a CLI plugin for that?
it -> fit worked for my use case where I am "focusing" on specific tests. When I'm done I can fit -> it, and commit. (curious the consequences of fit in build pipeline... we'd want to force all fit and it to be executed).
fdescribe and fit are kind of ok solutions when you don't have many tests, but it slows down work later on. The perfect solution would be to be able to run ng test --spec=common/services/** which would build only the needed files.
I'll poke around and try to port the solution I have at work that involves temporary/generated test.ts that lists needed files instead of relying on require.context
Final solution for our team was to just use Jest.
Final solution for our team was to just use Jest.
Can you give an example, or link to one? I'd be interested.
@BirgitPohl we used the library https://github.com/thymikee/jest-preset-angular. They mention in their readme a tutorial example. It worked with minor adjustments (because we use aliases in tsconfig we had to put back in jest.config.js).
@BirgitPohl
What @blackholegalaxy said. Just follow the readme and everything should work out of the box.
Cool. That's Jest-specific, isn't it? I'm using Jasmine in my tests. I wonder if it has something like this too.
Im also looking for this. I would like a VS CODE plugin or something to test a single test each time im updating that test... I don't want to go into test.ts and change that regex :(
I updated Angular in my app from version 5.0.5 to version 7.2.4.
With version 5.0.5 I used the method that suggested @EugeneSnihovsky and everything worked well. After the upgrade tests do not run.
I use command "test": "ng test --watch=false --code-coverage --tags $tags". And in terminal i see Unknown option: '--tags' :(
Unfortunately for now I can't find any workaround to pass custom flag to angular cli. As quick and dirty workaround I modified this solution NOTE: only edits are shown below, not complete solution
- change in karma.conf.js
const argv = require('minimist')(process.argv.slice(2)),
tags = (argv.tags !== true) && argv.tags;
to
const tags = (process.env.tags !== 'true') && process.env.tags;
- in package.json return default ng cli script for tests
"scripts": {
"test": "ng test --watch=false --code-coverage"
}
- launch test script from terminal with tags environment variable NOTE: example will work only on linux and mac, for windows set environment variable syntax is different
tags=footer.component npm test
If you can't change test launch syntax (for example like me because of automatic scripts on gitlab CI) - you can implement more dirty workaround
- Use gulp tasks and in gulpfile.js
const gulp = require('gulp'),
shell = require('gulp-shell'));
gulp.task('ng-test', (callback) => runUnitTests(callback, false));
gulp.task('ng-test:watch', (callback) => runUnitTests(callback, true));
function runUnitTests(callback, watchMode) {
let argv = require('minimist')(process.argv.slice(2));
shell.task([
`tags=${argv.tags} ng test --watch=${watchMode} --code-coverage`
])(callback);
}
- in package.json
"scripts": {
"gulp": "gulp",
"test": "gulp ng-test --tags $tags",
"test:watch": "gulp ng-test:watch --tags $tags"
}
- launch single file tests as
npm test footer.component
@EugeneSnihovsky, I did the changes as you mentioned, but it tells me the "test.component" could not be found in workspace.
ng test test.component
Do we need to give the whole path or it takes automatically?
@trupti28 probably you should use npm test test.component instead of ng test test.component
When I try this I simply get the error output:
Project 'myTest.component' could not be found in workspace
so I add the --project flag (I have multiple projects in the workspace)
Then I get Unknown option: 'myTest.component'
With the command: ng test --project=my-project myTest.component
Solution for angular 8
Tested in OS X with "@angular-devkit/build-angular": "~0.802.2"
Modify your package scripts to
"scripts": {
"test": "function test() { cmd='ng test --watch=false --code-coverage'; if [ -n \"$1\" ]; then cmd=\"$cmd --include $1\"; fi; $cmd; }; test"
}
Usage has changed a bit
npm test **/sign-in.component.spec.ts
P.S: thanks @RomanKisilenko for help.
Hi,
"test": "function test() { cmd='ng test --watch=false --code-coverage'; if [ -n \"$1\" ]; then cmd=\"$cmd --include $1\"; fi; $cmd; }; test",

Not working for me with "@angular-devkit/build-angular": "^0.801.3",! This is mandatory?
@pacocom I am fairly sure that command referenced above only works on linux/mac and via bash command on windows. From the looks in the screenshot you are running it via standard cmd
I don't know!

I upadate to "@angular-devkit/build-angular": "^0.803.3",
This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.
Read more about our automatic conversation locking policy.
This action has been performed automatically by a bot.