Angular 2 karma unit tests, template error

607 views Asked by At

I've got a problem - when I try to configure testbed, it throws error

Failed: Uncaught (in promise): Failed to load /student-register.component.html

I tried to solve this problem by overriding the component and setting empty template, but I'll need to test integration with html too, I tried also to override component by changing setting templateUrl, but I tried every possibility, and it throws failed to load error. Also I tried to override using require

 template: require('./student-register.component.html')

but it thrown me 1000 errors about angular's ngmodels etc, I want to avoid using require then.

It's my spec file:

describe('Component: Student Register Component', () => {
    let component: StudentRegisterComponent;
    let fixture: ComponentFixture<StudentRegisterComponent>;
    beforeEach(async(() => {

        TestBed.configureTestingModule({
            imports: [
                HttpModule,
            ],
            providers: [
                { provide: 'ApiBaseUrl', useValue: 'localhost'},
                AuthenticationGuard,
                AuthService,
                DatePipe,
                FormBuilder,
                MockPictureUpload,
                { provide: ActivatedRoute, useValue: {} },
                { provide: ApiService, useClass: MockApiService},
                { provide: PictureUploadComponent, useClass: MockPictureUpload},
                { provide: Router, useValue: mockRouter }
            ],
            declarations: [StudentRegisterComponent, MockPictureUpload],
        })
            .overrideComponent(StudentRegisterComponent, {
                set: {
                    providers: [
                        MockPictureUpload,
                        { provide: ApiService, useClass: MockApiService},
                        { provide: PictureUploadComponent, useClass: MockPictureUpload},
                    ],
                    // template: require('./student-register.component.html')
                    // templateUrl: './student-register.html'
                    // template: ``
                }
            })
            .compileComponents();

    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(StudentRegisterComponent);
        component = fixture.componentInstance;
    });
}

There is my karma.conf.js:

module.exports = function(config) {
    var testWebpackConfig = require('./webpack.test.js')({env: 'test'});

    var configuration = {

        // base path that will be used to resolve all patterns (e.g. files, exclude)
        basePath: '',

        /*
         * Frameworks to use
         *
         * available frameworks: https://npmjs.org/browse/keyword/karma-adapter
         */
        frameworks: ['jasmine'],

        // list of files to exclude
        exclude: [ ],

        /*
         * list of files / patterns to load in the browser
         *
         * we are building the test environment in ./spec-bundle.js
         */
        files: [ { pattern: './config/spec-bundle.js', watched: false } ],

        /*
         * preprocess matching files before serving them to the browser
         * available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
         */
        preprocessors: { './config/spec-bundle.js': ['coverage', 'webpack', 'sourcemap'] },

        // Webpack Config at ./webpack.test.js
        webpack: testWebpackConfig,
        hostname: '127.0.0.1',
        coverageReporter: {
            type: 'in-memory'
        },

        remapCoverageReporter: {
            'text-summary': null,
            json: './coverage/coverage.json',
            html: './coverage/html'
        },

        // Webpack please don't spam the console when running in karma!
        webpackMiddleware: { stats: 'errors-only'},

        /*
         * test results reporter to use
         *
         * possible values: 'dots', 'progress'
         * available reporters: https://npmjs.org/browse/keyword/karma-reporter
         */
        reporters: [ 'mocha', 'coverage', 'remap-coverage' ],

        // web server port
        port: 9876,

        hostname: '127.0.0.1',

        // enable / disable colors in the output (reporters and logs)
        colors: true,
        DEFAULT_TIMEOUT_INTERVAL: 5000,
        /*
         * level of logging
         * possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
         */
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        /*
         * start these browsers
         * available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
         */
        browsers: [
            'PhantomJS'
        ],

        customLaunchers: {
            ChromeTravisCi: {
                base: 'Chrome',
                flags: ['--no-sandbox']
            }
        },

        /*
         * Continuous Integration mode
         * if true, Karma captures browsers, runs the tests and exits
         */
        singleRun: true
    };

    if (process.env.TRAVIS){
        configuration.browsers = [
            'ChromeTravisCi'
        ];
    }

    config.set(configuration);
};

And tsconfig.json:

{
  "strictNullChecks": false,
  "compilerOptions": {
    "baseUrl": "",
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "noEmit": true,
    "noEmitHelpers": false,
    "outDir": "",
    "types": [
      "hammerjs",
      "jasmine",
      "node",
      "selenium-webdriver",
      "source-map",
      "uglify-js",
      "webpack"
    ],
    "paths": {
    },
    "lib": [
      "dom",
      "es6"
    ]
  },
  "exclude": [
    "node_modules",
    "dist",
    "**/*.spec.ts"
  ],
  "awesomeTypescriptLoaderOptions": {
    "forkChecker": true,
    "useWebpackText": true
  },
  "compileOnSave": false,
  "buildOnSave": false,
  "atom": { "rewriteTsconfig": false },
  "typeRoots": [
    "node_modules/@types"
  ]
}

Thanks :)

0

There are 0 answers