Blog>
Snippets

Automated Testing Setup in Angular Monorepo

Code examples of setting up a testing framework that enables automated testing across all apps and libs in the Angular monorepo.
module.exports = {
  projects: [
    '<rootDir>/apps/*',
    '<rootDir>/libs/*'
  ],
  testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'],
  transform: {
    '^.+\.(ts|js|html)$': 'jest-preset-angular',
  },
  moduleNameMapper: {
    '@core/(.*)': '<rootDir>/libs/core/$1',
    '@state/(.*)': '<rootDir>/libs/state/$1',
    ...
  }
};
This is a Jest configuration file snippet to set up automated testing in an Angular monorepo. It defines test patterns and specifies the directories for the apps and libs to include in testing. It also provides transformers and module name mappers for handling files and path aliases.
const { execSync } = require('child_process');

function runTestsForProject(project) {
  try {
    execSync(`ng test ${project}`, { stdio: 'inherit' });
  } catch (error) {
    console.error(`Failed to run tests for ${project}: ${error}`);
  }
}

function runAllTests() {
  const projects = ['my-app1', 'my-app2', 'my-lib'];

  projects.forEach(runTestsForProject);
}

runAllTests();
This is a Node.js script that iterates through all specified Angular apps and libs within a monorepo and triggers the `ng test` command for each project. It handles errors and logs them if a test suite fails to execute.
// karma.conf.js
module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, '../../coverage'),
      reports: ['html', 'lcovonly', 'text-summary'],
      fixWebpackSourcePaths: true
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    restartOnFileChange: true
  });
};
This is a configuration for Karma, a test runner commonly used in Angular projects. It sets up the framework, plugins, reporters, and browser launchers for executing tests in the monorepo.