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

Error trying to test an Angular2 component with an external template

我一直在尝试熟悉 Angular2 应用程序中的单元测试,并一直在关注 Angular 测试文档,但 运行 遇到错误我还没有一直想不通。

我有一个简单的演示应用程序,我将其放在一起进行测试。我的设置和配置与我的完整项目完全一样。它是一个 Angular2 应用程序,构建在 ASP.NET 核心 MVC 之上,使用此处提供的模板和设置 (https://marketplace.visualstudio.com/items?itemName=MadsKristensen.ASPNETCoreTemplatePack)。我将 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];

看来我已经解决了我的问题。在设置项目时,我显然安装了一个旧版本的 '@types/jasmine',它显然对 beforeEach() 具有不同的方法签名,无法接受 async() 函数返回的 done:any。我将 '@types/jasmine' 文件更新到最新版本,它支持该版本 beforeEach() 我所有的错误都消失了。