Search code examples
angularng-mocks

How to add ng-mocks to a fresh Angular 15 project


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?


Solution

  • 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.json (if that is located within src then skip the src/ prefix from the path):

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

    profit, now you can extend test.ts again.