尝试使用外部模板测试Angular2组件时出错

时间:2017-01-26 17:11:03

标签: angular typescript webpack jasmine karma-runner

我一直在尝试在Angular2应用程序中熟悉单元测试,并且一直在关注测试的Angular文档,但遇到了一个我无法弄清楚的错误。

我有一个简单的演示应用程序,我已经放在一起玩测试。我有它的设置和配置完全像我的完整项目。它是一个使用此处提供的模板和设置(https://marketplace.visualstudio.com/items?itemName=MadsKristensen.ASPNETCoreTemplatePack)构建在ASP.NET Core MVC之上的Angular2应用程序。我正在使用Webpack和Typescript与Karma和Jasmine进行单元测试。

我遇到的问题是,当我尝试使用外部模板(https://angular.io/docs/ts/latest/guide/testing.html#!#async-in-before-each)实现组件的测试时,我在async beforeEach函数上收到错误。虽然我的所有测试都成功通过,但我在编辑器中运行错误并在运行完整的应用程序时出错。我收到的错误是:error TS2345: Argument of type '(done: any) => any' is not assignable to parameter of type '() => void'.

虽然我的首选解决方案是修复错误,但由于我的测试正在通过,我决定配置内容,以便我的.spec.ts文件不包含在Webpack为prod站点创建的包中(注意我的spec.ts文件与实现组件的.ts文件并存。

banner.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { BannerComponent } from '../banner.component';

describe('BannerComponent (templateUrl)', () => {

    let comp: BannerComponent;
    let fixture: ComponentFixture<BannerComponent>;
    let de: DebugElement;
    let el: HTMLElement;

    // async beforeEach
    //This is the function that is producing the error
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [BannerComponent], // declare the test component
        })
        .compileComponents();  // compile template and css
    }));

    // synchronous beforeEach
    beforeEach(() => {
        fixture = TestBed.createComponent(BannerComponent);

        comp = fixture.componentInstance; // BannerComponent test instance

        // query for the title <h1> by CSS element selector
        de = fixture.debugElement.query(By.css('h1'));
        el = de.nativeElement;
    });

    it('no title in the DOM until manually call `detectChanges`', () => {
        expect(el.textContent).toEqual('');
    });

    it('should display original title', () => {
        fixture.detectChanges();
        expect(el.textContent).toContain(comp.title);
    });

    it('should display a different test title', () => {
        comp.title = 'Test Title';
        fixture.detectChanges();
        expect(el.textContent).toContain('Test Title');
    });

});

karma.conf.js:

'use strict';

module.exports = (config) => {
    config.set({
        autoWatch: true,
        browsers: ['Chrome', 'PhantomJS'],
        files: [
            './node_modules/es6-shim/es6-shim.min.js',
            './karma.entry.js'
        ],
        frameworks: ['jasmine'],
        logLevel: config.LOG_INFO,
        phantomJsLauncher: {
            exitOnResourceError: true
        },
        preprocessors: {
            'karma.entry.js': ['webpack', 'sourcemap']
        },
        reporters: ['progress', 'growl'],
        singleRun: false,
        webpack: require('./webpack.config.test'),
        webpackMiddleware: {
            noInfo: true
        }
    });
};

karma.entry.js

require('es6-shim');
require('reflect-metadata');
require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
require('zone.js/dist/sync-test');
require('zone.js/dist/proxy'); // since zone.js 0.6.14
require('zone.js/dist/jasmine-patch');

const browserTesting = require('@angular/platform-browser-dynamic/testing');
const coreTesting = require('@angular/core/testing');

coreTesting.TestBed.resetTestEnvironment();
coreTesting.TestBed.initTestEnvironment(
    browserTesting.BrowserDynamicTestingModule,
    browserTesting.platformBrowserDynamicTesting()
);

const context = require.context('./ClientApp/app/', true, /\.spec\.ts$/);

context.keys().forEach(context);

Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 2000;

webpack.config.test.js

'use strict';

const path = require('path');
const webpack = require('webpack');

module.exports = {
    devtool: 'inline-source-map',
    module: {
        loaders: [
            { loader: 'raw', test: /\.(css|html)$/ },
            { test: /\.ts$/, exclude: /node_modules/, include: /ClientApp/, loader: 'ts', query: { silent: true } },
            { test: /\.(png|jpg|jpeg|gif|woff|woff2|eot|ttf|svg)(\?|$)/, loader: 'url-loader?limit=100000' },
        ]
    },
    resolve: {
        extensions: ['', '.js', '.ts'],
        modulesDirectories: ['node_modules'],
        root: path.resolve('.', 'ClientApp/app')
    }
};

webpack.config.js

/// <binding ProjectOpened='Watch - Development' />
var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var nodeExternals = require('webpack-node-externals');
var merge = require('webpack-merge');
var allFilenamesExceptJavaScript = /\.(?!js(\?|$))([^.]+(\?|$))/;

// Configuration in common to both client-side and server-side bundles
var sharedConfig = {
    resolve: { extensions: [ '', '.js', '.ts' ] },
    output: {
        filename: '[name].js',
        publicPath: '/dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
    },
    module: {
        loaders: [
            { test: /\.ts$/, include: /ClientApp/, loader: 'ts', query: { silent: true } },
            { test: /\.html$/, loader: 'raw' },
            { test: /\.css$/, loader: 'to-string!css' },
            { test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'url', query: { limit: 25000 } }
        ]
    }
};

// Configuration for client-side bundle suitable for running in browsers
var clientBundleConfig = merge(sharedConfig, {
    entry: { 'main-client': './ClientApp/boot-client.ts' },
    output: { path: path.join(__dirname, './wwwroot/dist') },
    devtool: isDevBuild ? 'inline-source-map' : null,
    plugins: [
        new webpack.DllReferencePlugin({
            context: __dirname,
            manifest: require('./wwwroot/dist/vendor-manifest.json')
        })
    ].concat(isDevBuild ? [] : [
        // Plugins that apply in production builds only
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin()
    ])
});

// Configuration for server-side (prerendering) bundle suitable for running in Node
var serverBundleConfig = merge(sharedConfig, {
    entry: { 'main-server': './ClientApp/boot-server.ts' },
    output: {
        libraryTarget: 'commonjs',
        path: path.join(__dirname, './ClientApp/dist')
    },
    target: 'node',
    devtool: 'inline-source-map',
    externals: [nodeExternals({ whitelist: [allFilenamesExceptJavaScript] })] // Don't bundle .js files from node_modules
});

module.exports = [clientBundleConfig, serverBundleConfig];

1 个答案:

答案 0 :(得分:0)

看起来我已经弄明白了我的问题。在设置项目时,我显然安装了'@types/jasmine'的旧版本,显然有beforeEach()的不同方法签名无法接受完成:async()函数返回的任何方法签名。我将'@types/jasmine'文件更新为最新版本,该版本支持beforeEach()版本的所有错误消失了。