angularunit-testingsass

how to import styles correctly so that unit tests work in Angular?


I have a problem with unit test in angular. When i run ng test i have a errors with import scss.

This is an error:

./src/app/modules/auth/components/login/login.component.scss?ngResource - Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):     
Can't find stylesheet to import.
 @import "styles"

And this is a scss file:

    @import "styles";

   .login-container {
    @extend .center-page;
}

Styles.scss:

@import "node_modules/angular-notifier/styles";

@import "./utils/variables";
@import "./utils/extends";
@import "./utils/mixins";

I try to different ways to import style files.


Solution

  • You have a SCSS import issue.

    Configure stylePreprocessorOptions in angular.json: Add the following to your angular.json to fix path resolution:

            "test": {
              "builder": "@angular-devkit/build-angular:karma",
              "options": {
                "polyfills": [
                  "zone.js",
                  "zone.js/testing"
                ],
                "tsConfig": "tsconfig.spec.json",
                "inlineStyleLanguage": "scss",
                "assets": [
                  "src/favicon.ico",
                  "src/assets"
                ],
                "styles": [
                  "src/styles.scss"
                ],
                "stylePreprocessorOptions": {
                  "includePaths": [
                    "src"
                  ]
                }
                "scripts": []
              }
            }
    

    This allows you to import SCSS files as if starting from the src directory, making paths like @import "styles"; valid

    Here is an example:

      // src/app/app.component.scss
      // A relative path works
      @import '../style-paths/variables';
    
      // But now this works as well
      @import 'variables';