Angular 2业力单元测试,模板错误

时间:2017-08-29 13:23:13

标签: html typescript angular2-template karma-mocha angular2-testing

我遇到了问题 - 当我尝试配置testbed时,它会抛出错误

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

我试图通过覆盖组件和设置空模板来解决这个问题,但我也需要测试与html的集成,我还尝试通过更改设置templateUrl来覆盖组件,但我尝试了所有可能性,并且它抛出无法加载错误。 我也尝试使用require

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

但是它给了我1000个关于angular的ngmodels等的错误,我想避免使用require。

这是我的spec文件:

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;
    });
}

有我的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);
};

和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"
  ]
}

谢谢:)

0 个答案:

没有答案