pajevic
pajevic

Reputation: 4657

Cannot run Jest tests for components (Failed to load html files)

I am not able to run Jest tests on my components since it is not able to load html files. I get this error:

Error: Error: connect ECONNREFUSED 127.0.0.1:80

Followed by:

Unhandled Promise rejection: Failed to load landing.component.html

Running non-component tests is fine.

Here is my jest.config.js

/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
  preset: "jest-preset-angular",
  testEnvironment: "jsdom",
  setupFilesAfterEnv: ["<rootDir>/setup-jest.ts"],
  globals: {
    "ts-jest": {
      tsconfig: "<rootDir>/tsconfig.spec.json",
      stringifyContentPathRegex: "\\.(html|svg)$",
    },
  },
  snapshotSerializers: [
    "jest-preset-angular/build/serializers/html-comment",
    "jest-preset-angular/build/serializers/ng-snapshot",
    "jest-preset-angular/build/serializers/no-ng-attributes",
  ],
  moduleDirectories: ["node_modules", "."],
  testMatch: ["**/+(*.)+(spec|test).+(ts|js)?(x)"],
  transform: {
    "^.+\\.(ts|js|html)$": "ts-jest",
  },
  resolver: "@nrwl/jest/plugins/resolver",
  moduleFileExtensions: ["ts", "js", "html"],
  coverageReporters: ["html"],
};

My setup-jest.ts

import 'jest-preset-angular/setup-jest';

And my tsconfig.spec.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "module": "commonjs",
    "types": ["jest", "node"],
    "allowJs": true,
    "esModuleInterop": true,
    "emitDecoratorMetadata": true
  },
  "files": ["setup-jest.ts"],
  "include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}

And the Jest portion from angular.json

"test": {
  "builder": "@nrwl/jest:jest",
  "options": {
    "jestConfig": "jest.config.js",
    "passWithNoTests": true
  }
}

I am using Angular 12.2.7, Jest 27.2.4, jest-preset-angular 10.0.1 and ts-jest 27.0.5.

Upvotes: 5

Views: 1533

Answers (1)

Aaron Meese
Aaron Meese

Reputation: 2213

This answer helped me to solve this problem. As link-only answers are discouraged, below I have included the original answer by bnjmnhndrsn.

I encountered this specific problem recently and creating your own transform preprocesser will solve it. This was my set up:

package.json

"jest": {
    "moduleFileExtensions": [
      "js",
      "html"
    ],
    "transform": {
      "^.+\\.js$": "babel-jest",
      "^.+\\.html$": "<rootDir>/test/utils/htmlLoader.js"
    }
}

NOTE: babel-jest is normally included by default, but if you specify a custom transform preprocessor, you seem to have to include it manually.

test/utils/htmlLoader.js:

const htmlLoader = require('html-loader');

module.exports = {
    process(src, filename, config, options) {
        return htmlLoader(src);
    }
}

Upvotes: 1

Related Questions