测试模块无法解析正在测试的模块[Angular4,Karma,Jasmine] [英] Test module can't resolve module being tested [Angular4, Karma, Jasmine]

查看:83
本文介绍了测试模块无法解析正在测试的模块[Angular4,Karma,Jasmine]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个作为演示项目创建的小型TypeScript应用程序.它正在使用Angular 4,Karma,Webpack 2和Jasmine.

I have a small TypeScript app created as a demo project. It is using Angular 4, Karma, Webpack 2 and Jasmine.

该应用程序构建成功,我可以在浏览器中运行它.

The app builds successfully and I can run it in a browser.

测试不起作用,当我在命令行中运行karma start时,我看到这样的消息:

The tests do not work, when I run karma start in the command line, I see a message like this:

./app/welcome/app.welcome.spec.ts中的错误 找不到模块:错误:无法解析"D:\ ng-ts-demo \ app \ welcome"中的"./app.welcome"
@ ./app/welcome/app.welcome.spec.ts 4:20-44
@ ./app .spec.ts
@ ./app/test-main.ts

ERROR in ./app/welcome/app.welcome.spec.ts Module not found: Error: Can't resolve './app.welcome' in 'D:\ng-ts-demo\app\welcome'
@ ./app/welcome/app.welcome.spec.ts 4:20-44
@ ./app .spec.ts
@ ./app/test-main.ts

奇怪的是,app.welcome.ts文件与app.welcome.spec.ts位于同一目录中,但仍然找不到它!从消息中可以看出,问题是由test-main.ts文件而不是* .ts文件(仅* .spec.ts文件)加载引起的.

The weird thing is, the app.welcome.ts file is in the same directory as app.welcome.spec.ts but still it cannot find it! From the message it appears that the problem is caused by the test-main.ts file not loading the *.ts files, only the *.spec.ts files.

我已遵循Angular 4/Webpack官方指南此处,但我似乎没有缺少关键的东西.

I've followed the official Angular 4/Webpack guide here and I do not seem to be missing anything critical.

这是我的test-main.ts文件:

Here is my test-main.ts file:

Error['stackTraceLimit'] = Infinity;

import 'core-js/es7/reflect';
import 'reflect-metadata';
import 'zone.js';
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/proxy';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';

import { TestBed } from '@angular/core/testing';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';

let appContext = require.context('./', true, /\.spec\.ts/); // is this line the problem?

appContext.keys().forEach(appContext);

TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());

这是我的Karma.conf.js文件:

Here is my Karma.conf.js file:

'use strict';

const webpack = require('webpack');

module.exports = function(config) {
    config.set({

        basePath: '',
        frameworks: ['jasmine'],
        files: [
            { pattern: './app/test-main.ts' }
        ],
        exclude: [],
        preprocessors: {
            './app/test-main.ts': ['webpack', 'sourcemap']
        },
        reporters: ['progress'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: false,
        browsers: ['ChromeHeadless'],
        customLaunchers: {
            ChromeHeadless: {
                base: 'Chrome',
                flags: [
                  '--headless',
                  '--remote-debugging-port=9222',
                  '--disable-gpu',
                  '--disable-plugins',
                  '--window-size=0,0',
                  '--window-position=-9999,0'
                ],
            },
        },
        singleRun: true,
        concurrency: Infinity,
        webpack: {
            module: {
                rules: [{
                    test: /\.ts$/,
                    use: [
                        {
                            loader: 'awesome-typescript-loader',
                            options: {
                                configFileName: './tsconfig.json'
                            }
                        },
                        'angular2-template-loader'
                    ]
                }]
            },
            devtool: 'inline-source-map',
            plugins: [
                new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)@angular/, './app')
            ]
        },
        webpackMiddleware: {
            stats: 'errors-only'
        },
        webpackServer: {
            noInfo: true
        }
    });
}

这是app.welcome.spec.ts文件:

Here is the app.welcome.spec.ts file:

import { TestBed }            from '@angular/core/testing';
import { WelcomeComponent }   from './app.welcome';

describe('The Welcome component', function () {

    let component: WelcomeComponent;

    beforeEach(function() {
        TestBed.configureTestingModule({
            declarations: [WelcomeComponent]
        });

        let fixture = TestBed.createComponent(WelcomeComponent);
        component = fixture.componentInstance;
    });

    it('should be a component', function() {
        expect(component).toBeDefined();
    });

    it('should have a welcome message', function () {
        expect(component.welcomeMessage).toEqual('Welcome to TypeScript!');
    });

});

这是app.welcome.ts模块(与spec文件位于同一文件夹中,但神秘地找不到):

And here is the app.welcome.ts module (which is in the same folder as the spec file, but mysteriously cannot be found):

import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    template: '<h1>{{welcomeMessage}}</h1>',
})

export class WelcomeComponent {
    welcomeMessage = 'Welcome to TypeScript!';
}

推荐答案

在解决此问题时需要解决许多问题.第一个解决方法是在karma.conf.js中的webpack配置中添加一个解析配置:

There were a number of issues to overcome in getting this working. The first fix was to add a resolve config to the webpack config within karma.conf.js:

resolve: {
    extensions: ['.js', '.ts']
},

这解决了我的测试文件无法导入他们正在测试的文件的问题.

This solved the problem of my test files not being able to import the files they were testing.

这会导致第二个问题-测试文件本身没有被执行(运行测试时,我可以在命令行输出中看到Executed 0 of 0 ERROR.调试测试(通过将singleRun设置为false并将将浏览器从ChromeHeadless更改为常规Chrome时,在控制台中显示错误:

This then lead to the second problem - the test files themselves were not being executed (I could see Executed 0 of 0 ERROR in the command line output when running the test. Debugging the test (by setting singleRun to false and changing browser from ChromeHeadless to regular Chrome showed an error in the console:

拒绝从' http://localhost:9876/base/test-main执行脚本.ts ",因为其MIME类型("video/mp2t")不可执行.

Refused to execute script from 'http://localhost:9876/base/test-main.ts' because its MIME type ('video/mp2t') is not executable.

这是一个影响Chrome 55+的新问题,目前需要稍作修改.我必须将其添加到karma.conf.js文件中(虽然不在webpack config部分中):

This is a new issue affecting Chrome 55+ and there is a slightly hacky fix that is needed for now; I had to add this to the karma.conf.js file (not in the webpack config section though):

mime: {
    'text/x-typescript': ['ts']
}, 

此提示在问题中获得.终于,现在测试正在运行:)

This tip was picked up in this issue. Finally now the tests are running :)

现在也可以开始报道了...

Now to get coverage working also...

这篇关于测试模块无法解析正在测试的模块[Angular4,Karma,Jasmine]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆