4

如果我的应用程序代码使用取决于 moment.js 库的 ng2-boostrap 模块,我将无法在 Karma 中运行 jasmine 测试。

该应用程序在浏览器中运行良好,并且可以在浏览器中运行 jasmine 测试,方法是向系统添加即时映射:

-- unit-test.html ---
...
<script src="node_modules/ng2-bootstrap/bundles/ng2-bootstrap.min.js"></script>
...
<body>
<script>
    // #2. Configure SystemJS to use the .js extension
    //     for imports from the app folder
    System.config({
        packages: {
            'app': {defaultExtension: 'js'}
        },
        map: {
            'moment': 'node_modules/moment/moment.js'
        }
    });

我尝试在 karma.shim 内部进行相同的操作,但它不起作用。我正进入(状态:

 Error: XHR error (404 Not Found) loading http://localhost:9876/node_modules/moment/moment.js
 Error loading http://localhost:9876/node_modules/moment/moment.js as "moment" from http://localhost:9876/ng2-bootstrap/components/datepicker/date-formatter
 at addToError (D:/Projects/Angular/karma-ngbootstrap/node_modules/systemjs/dist/system.src.js:41:18)   

在我的 karma.conf 我有

files: [
    ...
    {pattern: 'node_modules/angular2/bundles/testing.dev.js', included: true, watched: true},    
    ....
    {pattern: 'node_modules/moment/moment.js',included: true, watched: true},
    {pattern: 'node_modules/ng2-bootstrap/bundles/ng2-bootstrap.min.js', included: true, watched: true},

    {pattern: 'karma-test-shim.js', included: true, watched: true},

    {pattern: 'app/**/*.js', included: false, watched: true},
    ....

在 karma-test-shim 中:

System.config({
    packages: {
        'base/app': {
            defaultExtension: false,
            format: 'register',
            map: Object.keys(window.__karma__.files).
            filter(onlyAppFiles).
            reduce(function createPathRecords(pathsMapping, appPath) {
                // creates local module name mapping to global path with karma's fingerprint in path, e.g.:
                // './hero.service': '/base/src/app/hero.service.js?f4523daf879cfb7310ef6242682ccf10b2041b3e'
                var moduleName = appPath.replace(/^\/base\/app\//, './').replace(/\.js$/, '');
                pathsMapping[moduleName] = appPath + '?' + window.__karma__.files[appPath]
                return pathsMapping;
            }, {})
        }
    },
    map: {
        'moment': 'node_modules/moment/moment.js'
    }
});

映射部分的工作原理取决于我放在那里的内容,moment我稍后会在 XHR 错误路径中得到它。

完整的文件可以在简单的测试项目中找到: https ://github.com/tzielins/angular-start-project

业力配置基于http://twofuckingdevelopers.com/2016/01/testing-angular-2-with-karma-and-jasmine/

我很高兴使用更简单的配置,但是我很幸运能够从头开始使用 System.js/Karma,而且这个没有 ng2-boostrap 依赖项也可以工作(测试中的代码仅从 ng2-boostrap 导入,这足以消除业力,可以将其注释掉以使测试通过)。

我必须从 System.js 配置中遗漏一些明显的东西。

4

1 回答 1

0

我正在使用带有角种子的新“ng2-bootstrap”-“ ngx-bootstrap ” ,也遇到了同样的问题。

修复了问题 - 在文件部分下的“karma.conf.js”中添加以下代码:

{pattern: 'node_modules/ngx-bootstrap/bundles/ngx-bootstrap.umd.min.js', included: false, watched: false}
于 2017-05-04T12:28:08.217 回答