styopdev
styopdev

Reputation: 2664

Inbuilt pipes cause failures when unit testing Angular 2 component

I have sample component which I would like to test. When I am using custom pipe (e.g my custom pipe concat) its working fine.

import { ConcatPipe } from 'path-to-concat-pipe';

@Component({
  selector: 'test',
  template: '{{ testProp | concat }}'
})
class TestComp {
  public testProp: Array = [2017, 2018];
}

But when I am trying to use inbuilt pipe (e.g. number), my tests are failing without any informative error message.

@Component({
  selector: 'test',
  template: '{{ testProp | number }}'
})
class TestComp {
  public testProp: number = 2017;
}

Sample spec code

describe('TestComp', () => {
    let comp: TestComp;
  let fixture: ComponentFixture<TestComp>;

  beforeEach(async(() => {
    TestBed
    .configureTestingModule({
      declarations: [TestComp, ConcatPipe],

    })
    .compileComponents()
    .then(() => {
          fixture = TestBed.createComponent(TestComp);        
          fixture.detectChanges();
    })
    }));

  it('TestComp successfully initialized', () => {
    expect(fixture.componentInstance).toBeDefined()
  });
});

Also, I have tried to import DecimalPipe from '@angular/common' and add it to declarations array but it cause error

Type DecimalPipe is part of the declarations of 2 modules: CommonModule and DynamicTestModule!

I am using angular 2.0 release version.

UPD

Test works fine in plunker @yurzui provided, but fails in my project. I guess issue may be related to my karma configuration files

karma.shim.js

'use strict';

Error.stackTraceLimit = Infinity;
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');
require('zone.js/dist/jasmine-patch');
require('@angular/core/testing');

var appContext = require.context('./src', true, /root.spec.ts/);

var testing = require('@angular/core/testing');
var browser = require('@angular/platform-browser-dynamic/testing');



testing.TestBed.initTestEnvironment(browser.BrowserDynamicTestingModule, browser.platformBrowserDynamicTesting());

karma.conf.js

'use strict';

var webpackConfig = require('./webpack.config');

module.exports = function (config) {
    var _config = {
        basePath: '',

        frameworks: ['jasmine'],

        files: [
            {pattern: './karma-shim.js', watched: false},
            {pattern: './src/app/**/*spec.ts', watched: true, included: false}
        ],

        exclude: [],

        preprocessors: {
            './karma-shim.js': ['webpack', 'sourcemap']
        },

        webpack: webpackConfig,

        webpackMiddleware: {
            stats: 'errors-only'
        },

        coverageReporter: {
            dir: 'coverage/',
            reporters: [
                {type: 'text-summary'},
                {type: 'html'}
            ]
        },

        browserNoActivityTimeout : 100000,

        webpackServer: {
            noInfo: true
        },

        reporters: ['story', 'coverage', 'progress'],

        port: 9876,

        colors: true,

        logLevel: config.LOG_DEBUG,

        autoWatch: false,

        browsers: ['PhantomJS'], 

        singleRun: true,
    };

    config.set(_config);

};

Upvotes: 1

Views: 2773

Answers (2)

styopdev
styopdev

Reputation: 2664

I found solution. Test was failing on PhantomJS browser but works on Chrome. Same issue is reproducable for angular-cli generated projects.

For getting angular 2 builtin pipes' tests working on PhantomJS then 2 lines of code should be added to

karma.shim.js if you are using generator-ng2-webpack.

require('intl');
require('intl/locale-data/jsonp/en');

or to

src/polyfills.ts in the case you are using angular-cli.

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

Upvotes: 0

yurzui
yurzui

Reputation: 214085

According to documentation https://angular.io/docs/ts/latest/cookbook/ngmodule-faq.html#!#q-what-to-declare

What classes should I add to declarations?

Add declarable classes — components, directives, and pipes — to a declarations list.

These classes must be declared in exactly one module of the application. Declare them in this module if they belong to this module.

So you should import CommonModule instead of pushing DecimalPipe to declarations array :

TestBed.configureTestingModule({
       imports: [CommonModule],

Upvotes: 3

Related Questions