Having karma tests outside src folder in angular 15 project
Asked Answered
R

1

6

I've had karma test spec files outside the src folder in a test folder on the root level of the project. After updating angular from 14 to 15, karma needs the test spec files to be in whatever folder the sourceRoot says in the angular.json file.

// angular.json
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "project-name": {
      "root": "",
      "sourceRoot": "", // <<===

Is there a way to tell karma to look at the workspace root level for test downwards without changing the sourceRoot attribute in angular.json?

I changed the sourceRoot path to "" and then Karma finds the tests as long as they're in the workspace folder and down, since i'm looking for tests with **/*.spec.ts in the

// tsconfig.spec.json
"include": [
    "**/*.spec.ts",
    "**/*.d.ts",
  ]
Repress answered 27/1, 2023 at 8:39 Comment(0)
R
9

So i'm going to answer my own question. This answer also leaves the sourceRoot value to whatever you choose. The answer is that in the angular.json file, you need to include the spec files in each project test configuration relative to the sourceRoot for that project configuration. Like so:

// angular.json
"test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "polyfills": ["zone.js/testing", "zone.js"],
            "tsConfig": "test/tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "include": [
              "../test/**/**.spec.ts",
              "../test/**/**.d.ts"
            ]
          }
        }

Then you also need to include those same files in the tsconfig.spec.json file relevant to each test configuration. Like so:

// tsconfig.spec.json
{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/spec",
    "types": [
      "jasmine",
      "node"
    ]
  },
  "files": [
    "../demo/src/polyfills.ts"
  ],
  "include": [
    "**/*.spec.ts"
  ]
}
Repress answered 27/1, 2023 at 10:36 Comment(3)
Thanks for your help ! I've resolved our problem with your suggestion !Conservative
Code coverage report doesn't work for me but all tests are executedMarceline
Thanks for your help, you save me hours of researches !! <3Glucoprotein

© 2022 - 2024 — McMap. All rights reserved.