如何在 Karma 中配置 System.js 以测试取决于时刻.js的代码

How to configure System.js in Karma to test code that depends on moment.js

本文关键字:js 测试 取决于 时刻 代码 System Karma 配置      更新时间:2023-09-26

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

该应用程序在浏览器中运行

良好,并且可以通过向系统添加映射来在浏览器中运行茉莉花测试:

-- 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)   

在我的业力中,我有

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},
    ....

在业力测试垫片中:

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 导入,这足以绊倒业力,可以注释掉以通过测试)。

我一定在系统.js配置中缺少一些明显的东西。

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

修复了此问题 - 将以下代码添加到"karma.conf.js",在文件部分下:

{pattern: 'node_modules/ngx-bootstrap/bundles/ngx-bootstrap.umd.min.js', included: false, watched: false}