2

I recently created a new Angular project using the latest Angular 15 CLI. Now I want to add ng-mocks to it.

I can install the dependency, but there is no longer a test.ts file where I can add the configuration for ng-mocks. When I add the file myself, my tests are no longer found.

What is the proper way to add ng-mocks to an Angular 15 project without test.ts?

jan.vdbergh
  • 2,129
  • 2
  • 20
  • 27

1 Answers1

4

now test.ts is generated by angular (node_modules/@angular-devkit/build-angular/src/builders/karma/index.js), if you want to customize it, you need to do the next:

create src/test.ts and put there:

import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting,
} from '@angular/platform-browser-dynamic/testing';

// Initialize the Angular testing environment.
getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), {
  errorOnUnknownElements: true,
  errorOnUnknownProperties: true
});

Then add it to angular.json:

        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts", // <- here
            "polyfills": [
              "zone.js",
              "zone.js/testing"
            ],
            "tsConfig": "tsconfig.spec.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          }
        }
      }

and add it to tsconfig.spec.ts:

  "include": [
    "src/test.ts", // <- here
    "src/**/*.spec.ts",
    "src/**/*.d.ts"
  ]

profit, now you can extend test.ts again.

satanTime
  • 12,631
  • 1
  • 25
  • 73
  • 1
    Ah I had a similar issue when upgrading a project from Angular v14 => v15 (as opposed to a fresh v15 project), but this helped me get that sorted out. Thank you! – Kurtis Jungersen Jun 29 '23 at 17:48