【问题标题】:Error trying to test an Angular2 component with an external template尝试使用外部模板测试 Angular2 组件时出错
【发布时间】:2017-01-26 17:11:03
【问题描述】:

我一直在尝试熟悉 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];

【问题讨论】:

  • 你没有在回调中执行任何异步工作,为什么还要使用 async(...)?
  • @AluanHaddad 这是异步的,因为被测组件有一个外部模板。由于需要读取该文件来创建组件并且它是一个异步操作,因此测试设置需要是异步的,以便在尝试创建组件的实例之前读取外部模板文件。您可以在 angular.io/docs/ts/latest/guide/… 的 Angular 文档中阅读更多相关信息

标签: angular typescript webpack jasmine karma-runner


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 2019-12-10
    相关资源
    最近更新 更多