angular-cli icon indicating copy to clipboard operation
angular-cli copied to clipboard

Run A Single Unit Test

Open jongunter opened this issue 9 years ago • 40 comments

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).

jongunter avatar Dec 16 '16 17:12 jongunter

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 avatar Jun 14 '18 02:06 danday74

@danday74 do you think it's possible to make a CLI plugin for that?

fetis avatar Jun 14 '18 08:06 fetis

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).

fizxmike avatar Sep 11 '18 15:09 fizxmike

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

FDIM avatar Nov 13 '18 14:11 FDIM

Final solution for our team was to just use Jest.

alexluecke avatar Nov 28 '18 04:11 alexluecke

Final solution for our team was to just use Jest.

Can you give an example, or link to one? I'd be interested.

BirgitPohl avatar Dec 05 '18 08:12 BirgitPohl

@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).

blackholegalaxy avatar Dec 05 '18 13:12 blackholegalaxy

@BirgitPohl

What @blackholegalaxy said. Just follow the readme and everything should work out of the box.

alexluecke avatar Dec 06 '18 05:12 alexluecke

Cool. That's Jest-specific, isn't it? I'm using Jasmine in my tests. I wonder if it has something like this too.

BirgitPohl avatar Dec 19 '18 17:12 BirgitPohl

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 :(

robvaneck avatar Dec 20 '18 10:12 robvaneck

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' :(

MaksKulykov avatar Feb 11 '19 14:02 MaksKulykov

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

  1. 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;
  1. in package.json return default ng cli script for tests
"scripts": {
    "test": "ng test --watch=false --code-coverage"
}
  1. 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

  1. 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);
}
  1. in package.json
"scripts": {
    "gulp": "gulp",
    "test": "gulp ng-test --tags $tags",
    "test:watch": "gulp ng-test:watch --tags $tags"
}
  1. launch single file tests as
npm test footer.component

EugeneSnihovsky avatar Feb 21 '19 10:02 EugeneSnihovsky

@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 avatar Feb 28 '19 20:02 trupti28

@trupti28 probably you should use npm test test.component instead of ng test test.component

EugeneSnihovsky avatar Mar 01 '19 06:03 EugeneSnihovsky

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

JAspeling avatar May 14 '19 05:05 JAspeling

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.

EugeneSnihovsky avatar Aug 22 '19 07:08 EugeneSnihovsky

Hi, "test": "function test() { cmd='ng test --watch=false --code-coverage'; if [ -n \"$1\" ]; then cmd=\"$cmd --include $1\"; fi; $cmd; }; test",

image

Not working for me with "@angular-devkit/build-angular": "^0.801.3",! This is mandatory?

pacocom avatar Sep 05 '19 07:09 pacocom

@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

FDIM avatar Sep 05 '19 08:09 FDIM

I don't know!

image

I upadate to "@angular-devkit/build-angular": "^0.803.3",

pacocom avatar Sep 05 '19 08:09 pacocom

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.