为什么我的单元测试通过Chrome并且使用PhantomJS失败?

时间:2016-10-09 08:22:29

标签: angular phantomjs angular-cli karma-runner angular-test

我正在使用Angular2 final(2.0.2)和angular-cli。 我正在尝试将其设置为使用PhantomJS运行单元测试。 使用Chrome和karma-chrome-launcher运行规范 - 所有测试都通过。 运行相同的Phantomjs-prebuilt 2.1.13和karma-phantomjs-launcher 1.0.2测试失败。

我将phantomjs启动程序添加到karma.conf中的plugins数组,以及浏览器数组中的PahntomJS。

我得到的错误是:

  

PhantomJS 2.1.1(Mac OS X 0.0.0)DataTableFormat应该转换日期   以毫秒为单位失败           ReferenceError:找不到变量:src / main / js / test.ts中的Intl(第53565行)           intlDateFormat @的WebPack:///Users/sninio/dev/csp-ui/~/@angular/common/src/facade/intl.js:117:0   < - src / main / js / test.ts:53565:20           的WebPack:///Users/sninio/dev/csp-ui/~/@angular/common/src/facade/intl.js:148:36   < - src / main / js / test.ts:53596:59           dateFormatter @的WebPack:///Users/sninio/dev/csp-ui/~/@angular/common/src/facade/intl.js:157:0   < - src / main / js / test.ts:53605:39           格式@的WebPack:///Users/sninio/dev/csp-ui/~/@angular/common/src/facade/intl.js:192:0   < - src / main / js / test.ts:53640:29           变换@的WebPack:///Users/sninio/dev/csp-ui/~/@angular/common/src/pipes/date_pipe.js:92:0   < - src / main / js / test.ts:70473:90           变换@的WebPack:///Users/sninio/dev/csp-ui/src/main/js/app/pages/+platform/events/data-table/data-table.pipe.ts:9:4418   < - src / main / js / test.ts:52698:5787           的WebPack:///Users/sninio/dev/csp-ui/src/main/js/app/pages/+platform/events/data-table/data-table.pipe.spec.ts:20:30   < - src / main / js / test.ts:60923:30           执行@的WebPack:///Users/sninio/dev/csp-ui/~/@angular/core/bundles/core-testing.umd.j   < - src / main / js / test.ts:2997:28           的WebPack:///Users/sninio/dev/csp-ui/~/@angular/core/bundles/core-testing.umd.js:951:32   < - src / main / js / test.ts:3084:56           调用@的WebPack:///Users/sninio/dev/csp-ui/~/zone.js/dist/zone.js:203:0   < - src / main / js / test.ts:98886:33           onInvoke @的WebPack:///Users/sninio/dev/csp-ui/~/zone.js/dist/proxy.js:72:0   < - src / main / js / test.ts:68790:45           调用@的WebPack:///Users/sninio/dev/csp-ui/~/zone.js/dist/zone.js:202:0   < - src / main / js / test.ts:98885:42           run @ webpack:///Users/sninio/dev/csp-ui/~/zone.js/dist/zone.js:96:0< -   的src /主/ JS / test.ts:98779:49           的WebPack:///Users/sninio/dev/csp-ui/~/zone.js/dist/jasmine-patch.js:91:27   < - src / main / js / test.ts:68526:53           执行@的WebPack:///Users/sninio/dev/csp-ui/~/zone.js/dist/jasmine-patch.js:119:0   < - src / main / js / test.ts:68554:46           执行@的WebPack:///Users/sninio/dev/csp-ui/~/zone.js/dist/jasmine-patch.js:119:0   < - src / main / js / test.ts:68554:46           invokeTask @的WebPack:///Users/sninio/dev/csp-ui/~/zone.js/dist/zone.js:236:0   < - src / main / js / test.ts:98919:42           runTask @的WebPack:///Users/sninio/dev/csp-ui/~/zone.js/dist/zone.js:136:0   < - src / main / js / test.ts:98819:57           drainMicroTaskQueue @的WebPack:///Users/sninio/dev/csp-ui/~/zone.js/dist/zone.js:368:0   < - src / main / js / test.ts:99051:42 PhantomJS 2.1.1(Mac OS X 0.0.0)   DataTableFormat应该转换日期字符串FAILED

也许我错过了angular-cli创建的test.ts文件中的一些配置?

更新 似乎只有导入失败的测试DatePipeJsonPipe 我还试图在@angular/common/testing中导入test.ts,但这没有帮助 - 它们不会在相关的index.js中导出。
还尝试导入整个@angular/common/pipes,但这也无效。

这是管道:

import { Pipe, PipeTransform } from "@angular/core";
import { DatePipe, JsonPipe } from "@angular/common";

@Pipe({name: 'dataTableFormat'})
export class DataTablePipe implements PipeTransform {

    // values with type 'json' are parsed to json. As a result, string values may be displayed with quotes ("<string>").
    // To avoid that, we remove these quotes with this regex
    private quotesExp: RegExp = /^\"|\"$/gi;

    constructor(private datePipe: DatePipe, private jsonPipe: JsonPipe) {

    }

    transform(value: any, type: string): string {
        switch (type) {
            case "date":
                return this.datePipe.transform(value, 'short');
            case "json":
                return this.jsonPipe.transform(value).replace(this.quotesExp, "");
            default:
                return value;
        }
    }
}

和规范:

import { inject, TestBed } from "@angular/core/testing";
import { DataTablePipe } from "./data-table.pipe";
import { DatePipe, JsonPipe } from "@angular/common";

describe('DataTableFormat', () => {

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
                DatePipe, JsonPipe
            ]
        });

    });

    it('should transform date in milliseconds', inject([DatePipe, JsonPipe], (datePipe, jsonPipe) => {
        let pipe = new DataTablePipe(datePipe, jsonPipe);
        let testDate: Date = new Date();

        expect(pipe.transform(testDate.getTime(), 'date')).toBe(datePipe.transform(testDate, 'short'));
    }));

    it('should transform date string', inject([DatePipe, JsonPipe], (datePipe, jsonPipe) => {
        let pipe = new DataTablePipe(datePipe, jsonPipe);
        let testDate: Date = new Date();

        expect(pipe.transform(testDate.toISOString(), 'date')).toBe(datePipe.transform(testDate, 'short'));
    }));

    it('should transform json', inject([DatePipe, JsonPipe], (datePipe, jsonPipe) => {
        let pipe = new DataTablePipe(datePipe, jsonPipe);
        let testJson = {
            prop1: "val1",
            prop2: "val2"
        };

        expect(pipe.transform(testJson, 'json')).toBe(jsonPipe.transform(testJson));
    }));

});

这是我的test.ts文件 - 与angular-cli生成的文件相比没有太大改变......

import "./polyfills.ts";
import "zone.js/dist/long-stack-trace-zone";
import "zone.js/dist/proxy.js";
import "zone.js/dist/sync-test";
import "zone.js/dist/jasmine-patch";
import "zone.js/dist/async-test";
import "zone.js/dist/fake-async-test";


// Unfortunately there's no typing for the `__karma__` variable. Just declare it as any.
declare var __karma__: any;
declare var require: any;

// Prevent Karma from running prematurely.
__karma__.loaded = function () {
};

//noinspection TypeScriptUnresolvedVariable
Promise.all([
    System.import('@angular/core/testing'),
    System.import('@angular/platform-browser-dynamic/testing'),
    System.import('../../../node_modules/nvd3/build/nv.d3.min.js'),
])
// First, initialize the Angular testing environment.
    .then(([testing, testingBrowser]) => {
        testing.getTestBed().initTestEnvironment(
            testingBrowser.BrowserDynamicTestingModule,
            testingBrowser.platformBrowserDynamicTesting()
        );
    })
    // Then we find all the tests.
    .then(() => require.context('./', true, /\.spec\.ts/))
    // And load the modules.
    .then(context => context.keys().map(context))
    // Finally, start Karma to run the tests.
    .then(__karma__.start, __karma__.error);

知道为什么这适用于Chrome而非PhantomJS?

3 个答案:

答案 0 :(得分:12)

由于PhantomJS没有实现Angular2依赖的Intl实现,解决方案是安装npm package intl polyfill并编辑polyfills.ts以包含

import 'intl';
import 'intl/locale-data/jsonp/en.js';

见这里:https://github.com/angular/angular/issues/3333
在这里:https://github.com/angular/angular/issues/10809
在这里:https://coryrylan.com/blog/adding-the-internationalization-polyfill-to-a-angular-cli-project

答案 1 :(得分:2)

现在您在所有浏览器中都支持Intl。 polyfill.io是一个漂亮的服务,只有在请求的浏览器实际需要它时才会加载polyfill。这是一个非常好的解决方案,但是如果您希望将polyfill与脚本捆绑在一起呢?您可能会获得更好的性能,并且您的应用程序不依赖于第三方CDN,如果它发生故障,它会使您的应用程序失效。那么下一个选择是什么?

使用Angular CLI它实际上非常简单。首先,我们将使用npm将Intl polyfill直接安装到我们的Angular应用程序中。要执行此操作,请运行npm install intl --save。安装在Angular CLI项目中后,转到/src/polyfills.ts文件。在这里,您可以添加以下行。

import 'intl';
import 'intl/locale-data/jsonp/en.js';

就是这样!现在,当您的项目构建时,它将添加Intl polyfill和英语语言服务。您可以通过导入更多语言文件来添加更多语言支持。现在的缺点是,即使浏览器支持Intl,它仍然必须下载代码。您可以使用功能检测和动态加载来减轻这种影响。关于polyfilling的重要部分是随着对Intl的浏览器支持变得更好,我们将能够一起放弃依赖!

答案 2 :(得分:0)

Intl实现在Angular中可用,在PhantomJS中则不可用。要使其与Polyfill一起使用,请按照以下步骤操作:

  1. 安装国际版: npm install intl --save
  2. 将以下导入添加到polyfills.ts文件中:

    导入'intl'; 导入'intl / locale-data / jsonp / en.js';