Angular2 testing with fakeAsync - unit-testing

I'm trying to use fakeAsync to test an Angular 2 component, but the fixture variable is not being set. In fact, the promise callback is not being called. Here is the code:
#Component({
template: '',
directives: [GroupBox, GroupBoxHeader]
})
class TestComponent {
expandedCallback() { this.expandedCalled = true; }
}
it('testing...', inject([TestComponentBuilder], fakeAsync((tcb) => {
var fixture;
tcb.createAsync(TestComponent).then((rootFixture) => {
fixture = rootFixture
});
tick();
fixture.detectChanges();
})));
When I run this code, I get:
Failed: Cannot read property 'detectChanges' of undefined
TypeError: Cannot read property 'detectChanges' of undefined
I can't figure out why the callback isn't fired. In this repository, it works fine: https://github.com/juliemr/ng2-test-seed/blob/master/src/test/greeting-component_test.ts
Any clue?
Note: I'm using ES6, Traceur, Angular 2 beta, Karma and Jasmine.
------ UPDATE ------
It follows a repository with the failing test:
https://github.com/cangosta/ng2_testing_fakeasync

TestComonentBuilder doesn't work with templateUrl https://github.com/angular/angular/issues/5662

Try this way
https://github.com/antonybudianto/angular2-starter/blob/master/app/simplebind/child.component.spec.ts#L15
The point is you create a test dummy component (TestComponent for example) and register the component you want to test in directives: [...] and use template: <my-cmp></my-cmp>, then pass the TestComponent to tsb.createAsync(TestComponent)..., and use injectAsync.
I prefer this way since I can easily mock the data from parent, and pass any input and handle output to/from the component.
import {
it,
injectAsync,
describe,
expect,
TestComponentBuilder,
ComponentFixture
} from 'angular2/testing';
import { Component } from 'angular2/core';
import { ChildComponent } from './child.component';
#Component({
selector: 'test',
template: `
<child text="Hello test" [(fromParent)]="testName"></child>
`,
directives: [ChildComponent]
})
class TestComponent {
testName: string;
constructor() {
this.testName = 'From parent';
}
}
let testFixture: ComponentFixture;
let childCompiled;
let childCmp: ChildComponent;
describe('ChildComponent', () => {
it('should print inputs correctly', injectAsync([TestComponentBuilder],
(tsb: TestComponentBuilder) => {
return tsb.createAsync(TestComponent).then((fixture) => {
testFixture = fixture;
testFixture.detectChanges();
childCompiled = testFixture.nativeElement;
childCmp = testFixture.debugElement.children[0].componentInstance;
expect(childCompiled).toBeDefined();
expect(childCmp).toBeDefined();
expect(childCompiled.querySelector('h6'))
.toHaveText('From parent');
expect(childCompiled.querySelector('h5'))
.toHaveText('Hello test');
});
}));
it('should trigger changeMe event correctly', () => {
childCmp.changeMe();
testFixture.detectChanges();
expect(childCmp.num).toEqual(1);
expect(childCompiled.querySelector('h6'))
.toHaveText('Changed from child. Count: ' + childCmp.num);
});
});

Related

debugElement return null in my angular5 test

I wish to test an anguar5 component using a host component as described in angular.io doc.
But my test keep failing because of
TypeError: Cannot read property 'query' of null
at UserContext.<anonymous> (http://localhost:9876/base/config-webpack/spec-bundle.js:293832:39)
at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/base/config-webpack/spec-bundle.js:288418:26)
at ProxyZoneSpec../node_modules/zone.js/dist/proxy.js.ProxyZoneSpec.onInvoke (http://localhost:9876/base/config-webpack/spec-bundle.js:287920:39)
at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/base/config-webpack/spec-bundle.js:288417:32)
at Zone../node_modules/zone.js/dist/zone.js.Zone.run (http://localhost:9876/base/config-webpack/spec-bundle.js:288168:43)
at UserContext.<anonymous> (http://localhost:9876/base/config-webpack/spec-bundle.js:287799:34)
at attempt (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:4289:46)
at ZoneQueueRunner.QueueRunner.run (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:4217:20)
at ZoneQueueRunner.QueueRunner.execute (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:4199:10)
at ZoneQueueRunner../node_modules/zone.js/dist/jasmine-patch.js.jasmine.QueueRunner.ZoneQueueRunner.execute (http://localhost:9876/base/config-webpack/spec-bundle.js:287827:42)
Indeed, when I log my fixture.debugElement, it return null.
my test code is :
import {} from 'jasmine';
import { Component } from '#angular/core';
import { TestBed, ComponentFixture } from '#angular/core/testing';
import { By } from '#angular/platform-browser';
import { DropDownListComponent } from './dropDownList.component';
#Component({
template: '<dropdown-list [valuesList]="valuesList" [selectedValue]="valuesSelected" ></dropdown-list>'
})
class TestComponent {
valuesList = [{label: 'test_select', value:'test'}, {label: 'test_select2', value:'test2'}];
valuesSelected = {label: 'test_select', value:'test'};
}
describe('DropDownListComponent', () => {
let fixture, component;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestComponent, DropDownListComponent]
}).compileComponents();
});
it('should display selectedValue', () => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
console.log(fixture.isStable());
console.log(fixture);
console.log(component);
console.log(fixture.debugElement);
//const fixture = TestBed.createComponent(TestComponent);
let de = fixture.debugElement.query(By.css(".value-container"));
let el = de.nativeElement;
expect(el.textContent).toContain('test_select');
});
});
When you write a test you need to test only your component / service / pipe / directive etc, but not its dependencies.
From the code above I assume DropDownListComponent has a DI dependency that wasn't declared in providers of TestBed and it causes the issue. Anyway in this context it should be a mock, not a real component.
If you want to test DropDownListComponent - then please share its code. Without understanding its interface it's hard to guess how to write tests for it.
You can use ng-mocks to mock it and then you would only need to test that [valuesList] and [selectedValue] got right values.
Also to compile all components correctly you need to handle compileComponents's promise.
describe('TestComponent', () => {
beforeEach(() => {
return TestBed.configureTestingModule({
declarations: [TestComponent, MockComponent(DropDownListComponent)],
}).compileComponents();
});
it('should display selectedValue', () => {
const fixture = MockRender(TestComponent);
const dropdown = MockHelper.findOrFail(fixture.debugElement, DropDownListComponent);
expect(dropdown.valuesList).toEqual(fixture.point.valuesList);
expect(dropdown.selectedValue).toEqual(fixture.point.valuesSelected);
});
});
Profit.

Unit test vue.js component with inline-template

I am using Vue 2 to enhance a Ruby on Rails engine, using inline-template attributes in the existing Haml views as templates for my Vue components.
Is it possible to test the methods of a component defined like this? All the testing examples I can find assume the use of single-file .vue components.
These tests (using Mocha and Chai) fail with [Vue warn]: Failed to mount component: template or render function not defined.
Example Component:
//main-nav.js
import Vue from 'vue'
const MainNav = {
data: function() {
return {open: true}
},
methods: {
toggleOpen: function(item) {
item.open = !item.open
}
}
}
export default MainNav
Example Test:
//main-nav.test.js
import MainNav from '../../admin/main-nav'
describe('MainNav', () => {
let Constructor
let vm
beforeEach(() => {
Constructor = Vue.extend(MainNav)
vm = new Constructor().$mount()
})
afterEach(() => {
vm.$destroy()
})
describe('toggleOpen', () => {
it('has a toggleOpen function', () => {
expect(vm.MainNav.toggleOpen).to.be.a('function')
})
it('toggles open from true to false', () => {
const result = MainNav.toggleOpen({'open': true})
expect(result).to.include({open: false})
})
})
})
It turns out you can still specify a template in the component file, and any inline-template templates will be used in favour of that.

Angular 2 unit testing data passed from parent component to child component

I have a question about the way I've seen (the very few) examples of testing of data passed down from a parent component into a child component. Currently, in the Angular2 docs, they're testing to see if data has been passed down from a parent component to a child by inspecting the dom values of the child component. The issue that I have with this approach is that it forces the parent's spec to know the html structure of the child component. The parent component's job is just to pass data into the child. An example...
I have a Story Component as follows:
'use strict';
import {Component, OnInit, Input} from '#angular/core';
import {StoryService} from '../../services/story.service';
import {StoryModel} from '../../models/story-model';
import {AlbumCover} from './album-cover/album-cover';
import {Author} from "./author/author";
import {StoryDuration} from "./story-duration/story-duration";
#Component({
selector: 'story',
templateUrl: 'build/components/story/story.html',
providers: [StoryService],
directives: [AlbumCover, Author, StoryDuration]
})
export class Story implements OnInit {
#Input('id') id:number;
public story:StoryModel;
constructor(private storyService:StoryService) {}
ngOnInit() {
this.getStory();
}
private getStory() {
this.storyService.getStory(this.id).subscribe(story => this.story = story);
}
}
Notice how it has an AlbumCover Component dependency in the directives array in the #Component decorator.
Here is my Story template:
<div *ngIf="story">
<album-cover [image]="story.albumCover" [title]="story.title"></album-cover>
<div class="author-duration-container">
<author [avatar]="story.author.avatar" [name]="story.author.name"></author>
<story-duration [word-count]="story.wordCount"></story-duration>
</div>
</div>
Notice the <album-cover [image]="story.albumCover" [title]="story.title"></album-cover> line where I'm binding the story.albumCover from the Story controller to the image property of the AlbumCover. This is all working perfectly. Now for the test:
import {provide} from '#angular/core';
import {beforeEach, beforeEachProviders, describe, expect, injectAsync, it, setBaseTestProviders, resetBaseTestProviders} from '#angular/core/testing';
import {HTTP_PROVIDERS} from '#angular/http';
import {BROWSER_APP_DYNAMIC_PROVIDERS} from "#angular/platform-browser-dynamic";
import {TEST_BROWSER_STATIC_PLATFORM_PROVIDERS, ADDITIONAL_TEST_BROWSER_PROVIDERS} from '#angular/platform-browser/testing';
import {ComponentFixture, TestComponentBuilder} from '#angular/compiler/testing';
import {Observable} from 'rxjs/Observable';
// TODO: this pattern of importing 'of' can probably go away once rxjs is fixed
// https://github.com/ReactiveX/rxjs/issues/1713
import 'rxjs/add/observable/of';
resetBaseTestProviders();
setBaseTestProviders(
TEST_BROWSER_STATIC_PLATFORM_PROVIDERS,
[BROWSER_APP_DYNAMIC_PROVIDERS, ADDITIONAL_TEST_BROWSER_PROVIDERS]
);
import {Story} from './story';
import {StoryModel} from '../../models/story-model';
import {StoryService} from '../../services/story.service';
var mockStory = {
id: 1,
title: 'Benefit',
albumCover: 'images/placeholders/story-4.jpg',
author: {
id: 2,
name: 'Brett Beach',
avatar: 'images/placeholders/author-1.jpg'
},
wordCount: 4340,
content: '<p>This is going to be a great book! I <strong>swear!</strong></p>'
};
class MockStoryService {
public getStory(id):Observable<StoryModel> {
return Observable.of(mockStory);
}
}
describe('Story', () => {
var storyFixture,
story,
storyEl;
beforeEachProviders(() => [
HTTP_PROVIDERS
]);
beforeEach(injectAsync([TestComponentBuilder], (tcb:TestComponentBuilder) => {
return tcb
.overrideProviders(Story, [
provide(StoryService, {
useClass: MockStoryService
})
])
.createAsync(Story)
.then((componentFixture:ComponentFixture<Story>) => {
storyFixture = componentFixture;
story = componentFixture.componentInstance;
storyEl = componentFixture.nativeElement;
componentFixture.detectChanges();
});
}));
describe(`ngOnInit`, () => {
describe(`storyService.getStory`, () => {
it(`should be called, and on success, set this.story`, () => {
spyOn(story.storyService, 'getStory').and.callThrough();
story.ngOnInit();
expect(story.storyService.getStory).toHaveBeenCalled();
expect(story.story.title).toBe('Benefit');
});
});
});
it('should not show the story component if story does not exist', () => {
story.story = null;
storyFixture.detectChanges();
expect(storyEl.children.length).toBe(0);
});
it('should show the story component if story exists', () => {
story.story = mockStory;
storyFixture.detectChanges();
expect(storyEl.children.length).not.toBe(0);
});
describe('story components', () => {
beforeEach(() => {
story.story = mockStory;
storyFixture.detectChanges();
});
describe('album cover', () => {
var element,
img;
beforeEach(() => {
element = storyEl.querySelector('album-cover');
img = element.querySelector('img');
});
it(`should be passed the story albumCover and title to the album cover component`, () => {
expect(img.attributes.src.value).toBe(mockStory.albumCover);
expect(img.attributes.alt.value).toBe(mockStory.title);
});
});
describe('author', () => {
var element,
img,
nameEl;
beforeEach(() => {
element = storyEl.querySelector('author');
img = element.querySelector('img');
nameEl = element.querySelector('.name');
});
it(`should be passed the author name and avatar`, () => {
expect(img.attributes.src.value).toBe(story.story.author.avatar);
expect(img.attributes.alt.value).toBe(story.story.author.name);
expect(nameEl.innerText).toBe(story.story.author.name);
});
});
describe('story duration', () => {
var element;
beforeEach(() => {
element = storyEl.querySelector('.story-duration');
});
it(`should be passed the word count to generate the total read time`, () => {
story.story.wordCount = 234234;
storyFixture.detectChanges();
expect(element.innerText).toBe(`852 min read`);
});
});
});
});
Look at my describe('album cover'.... The way I'm passing this expectation is that I'm finding the <album-cover> element, then finding the <img> tag inside of it, then checking the <img>'s DOM attributes. To me, this expection should be inside of the album-cover.spec.ts - NOT the story.spec.ts.
My question is: is there a way to test if a parent component passed data into a child component without relying on reading dom values?
You can use overrideTemplate to pass a view just for the test.
return tcb
.overrideTemplate(AlbumCover, '<div>{{valueFromParent}}</div>')
.overrideProviders(Story, [

Angular 2 unit test parsing error using webpack

I'm getting the follow error when I run Angular 2 unit test using webpack:
FAILED TESTS:
Other Trims Tested
✖ should display other trims articles
PhantomJS 2.1.1 (Linux 0.0.0)
Error: Template parse errors:
Unexpected closing tag "div" ("module.exports = "<div *ngFor=\"let trim of otherTrims\">\n {{ trim.name }}\n[ERROR ->]</div>\n\n<!--<div class='test-name'>{{ otherTrims[0].name }}</div>-->\n";"): OtherTrimsTestedComponent#0:78 in /app/config/spec-bundle.js (line 52805)
I see that it is testing webpacks bundle-js file but I am not sure if there is another import I have to do from angular core tests
I have my HTML setup as:
<div *ngFor="let trim of otherTrims">
{{ trim.name }}
</div>
and spec test as:
import {
it,
fdescribe,
expect,
inject,
async,
TestComponentBuilder
} from '#angular/core/testing';
import { OtherTrimsTestedComponent } from './other-trims-tested.component';
let mockData = [
{
'featured_image': 'http://test.url.com',
'article_type': 'Test',
'article_url': 'http://test.url.com',
'name': 'Ford F-150 Raptor',
'specs' : '4 Door AWD Pickup Truck, 150Bhp, 285 lb-ft, 8-sp Automatic',
'msrp': '50,000'
}
];
fdescribe('Other Trims Tested', () => {
it('should have a selector', () => {
let annotations = Reflect.getMetadata('annotations', OtherTrimsTestedComponent);
expect(annotations[0].selector).toBe('other-trims-tested');
});
it('should display other trims articles', async(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
return tcb.createAsync(OtherTrimsTestedComponent).then(fixture => {
// Get components
let otherTrimsTestedComponent = fixture.componentInstance; // Get component instance
let element = fixture.nativeElement; // Get test component elements
otherTrimsTestedComponent.otherTrims = mockData;
// Detect changes? (How?)
fixture.detectChanges();
// Test against data
expect(element.querySelector('.test-name').innerText).toBe('Ford F-150 Raptor2');
});
})));
});
and Component:
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'other-trims-tested',
template: require('./other-trims-tested.component.html')
})
export class OtherTrimsTestedComponent implements OnInit {
#Input() otherTrims: any[];
constructor() { }
ngOnInit() { }
}
Any hints/articles can help. Thanks
Have you added html-loader to your webpack test configuration?
rules: [
...
{
test: /\.html$/,
loader: 'raw-loader'
}
...
}

angular2 test, how do I mock sub component

How do I mock sub component in jasmine tests?
I have MyComponent, which uses MyNavbarComponent and MyToolbarComponent
import {Component} from 'angular2/core';
import {MyNavbarComponent} from './my-navbar.component';
import {MyToolbarComponent} from './my-toolbar.component';
#Component({
selector: 'my-app',
template: `
<my-toolbar></my-toolbar>
{{foo}}
<my-navbar></my-navbar>
`,
directives: [MyNavbarComponent, MyToolbarComponent]
})
export class MyComponent {}
When I test this component, I do not want to load and test those two sub components; MyNavbarComponent, MyToolbarComponent, so I want to mock it.
I know how to mock with services using provide(MyService, useClass(...)), but I have no idea how to mock directives; components;
beforeEach(() => {
setBaseTestProviders(
TEST_BROWSER_PLATFORM_PROVIDERS,
TEST_BROWSER_APPLICATION_PROVIDERS
);
//TODO: want to mock unnecessary directives for this component test
// which are MyNavbarComponent and MyToolbarComponent
})
it('should bind to {{foo}}', injectAsync([TestComponentBuilder], (tcb) => {
return tcb.createAsync(MyComponent).then((fixture) => {
let DOM = fixture.nativeElement;
let myComponent = fixture.componentInstance;
myComponent.foo = 'FOO';
fixture.detectChanges();
expect(DOM.innerHTML).toMatch('FOO');
});
});
Here is my plunker example;
http://plnkr.co/edit/q1l1y8?p=preview
As requested, I'm posting another answer about how to mock sub components with input/output:
So Lets start by saying we have TaskListComponent that displays tasks, and refreshes whenever one of them is clicked:
<div id="task-list">
<div *ngFor="let task of (tasks$ | async)">
<app-task [task]="task" (click)="refresh()"></app-task>
</div>
</div>
app-task is a sub component with the [task] input and the (click) output.
Ok great, now we want to write tests for my TaskListComponent and of course we don't want to test the real app-taskcomponent.
so as #Klas suggested we can configure our TestModule with:
schemas: [CUSTOM_ELEMENTS_SCHEMA]
We might not get any errors at either build or runtime, but we won't be able to test much other than the existence of the sub component.
So how can we mock sub components?
First we'll define a mock directive for our sub component (same selector):
#Directive({
selector: 'app-task'
})
class MockTaskDirective {
#Input('task')
public task: ITask;
#Output('click')
public clickEmitter = new EventEmitter<void>();
}
Now we'll declare it in the testing module:
let fixture : ComponentFixture<TaskListComponent>;
let cmp : TaskListComponent;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TaskListComponent, **MockTaskDirective**],
// schemas: [CUSTOM_ELEMENTS_SCHEMA],
providers: [
{
provide: TasksService,
useClass: MockService
}
]
});
fixture = TestBed.createComponent(TaskListComponent);
**fixture.autoDetectChanges();**
cmp = fixture.componentInstance;
});
Notice that because the generation of sub component of the fixture is happening asynchronously after its creation, we activate its autoDetectChanges feature.
In our tests, we can now query for the directive, access its DebugElement's injector, and get our mock directive instance through it:
import { By } from '#angular/platform-browser';
const mockTaskEl = fixture.debugElement.query(By.directive(MockTaskDirective));
const mockTaskCmp = mockTaskEl.injector.get(MockTaskDirective) as MockTaskDirective;
[This part should usually be in the beforeEach section, for cleaner code.]
From here, the tests are a piece of cake :)
it('should contain task component', ()=> {
// Arrange.
const mockTaskEl = fixture.debugElement.query(By.directive(MockTaskDirective));
// Assert.
expect(mockTaskEl).toBeTruthy();
});
it('should pass down task object', ()=>{
// Arrange.
const mockTaskEl = fixture.debugElement.query(By.directive(MockTaskDirective));
const mockTaskCmp = mockTaskEl.injector.get(MockTaskDirective) as MockTaskDirective;
// Assert.
expect(mockTaskCmp.task).toBeTruthy();
expect(mockTaskCmp.task.name).toBe('1');
});
it('should refresh when task is clicked', ()=> {
// Arrange
spyOn(cmp, 'refresh');
const mockTaskEl = fixture.debugElement.query(By.directive(MockTaskDirective));
const mockTaskCmp = mockTaskEl.injector.get(MockTaskDirective) as MockTaskDirective;
// Act.
mockTaskCmp.clickEmitter.emit();
// Assert.
expect(cmp.refresh).toHaveBeenCalled();
});
If you use schemas: [CUSTOM_ELEMENTS_SCHEMA]in TestBed the component under test will not load sub components.
import { CUSTOM_ELEMENTS_SCHEMA } from '#angular/core';
import { TestBed, async } from '#angular/core/testing';
import { MyComponent } from './my.component';
describe('App', () => {
beforeEach(() => {
TestBed
.configureTestingModule({
declarations: [
MyComponent
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
});
});
it(`should have as title 'app works!'`, async(() => {
let fixture = TestBed.createComponent(MyComponent);
let app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('Todo List');
}));
});
This works in the released version of Angular 2.0.
Full code sample here.
An alternative to CUSTOM_ELEMENTS_SCHEMA is NO_ERRORS_SCHEMA
Thanks to Eric Martinez, I found this solution.
We can use overrideDirective function which is documented here,
https://angular.io/docs/ts/latest/api/testing/TestComponentBuilder-class.html
It takes three prarmeters;
1. Component to implement
2. Child component to override
3. Mock component
Resolved solution is here at http://plnkr.co/edit/a71wxC?p=preview
This is the code example from the plunker
import {MyNavbarComponent} from '../src/my-navbar.component';
import {MyToolbarComponent} from '../src/my-toolbar.component';
#Component({template:''})
class EmptyComponent{}
describe('MyComponent', () => {
beforeEach(injectAsync([TestComponentBuilder], (tcb) => {
return tcb
.overrideDirective(MyComponent, MyNavbarComponent, EmptyComponent)
.overrideDirective(MyComponent, MyToolbarComponent, EmptyComponent)
.createAsync(MyComponent)
.then((componentFixture: ComponentFixture) => {
this.fixture = componentFixture;
});
));
it('should bind to {{foo}}', () => {
let el = this.fixture.nativeElement;
let myComponent = this.fixture.componentInstance;
myComponent.foo = 'FOO';
fixture.detectChanges();
expect(el.innerHTML).toMatch('FOO');
});
});
I put together a simple MockComponent module to help make this a little easier:
import { TestBed } from '#angular/core/testing';
import { MyComponent } from './src/my.component';
import { MockComponent } from 'ng2-mock-component';
describe('MyComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
MyComponent,
MockComponent({
selector: 'my-subcomponent',
inputs: ['someInput'],
outputs: [ 'someOutput' ]
})
]
});
let fixture = TestBed.createComponent(MyComponent);
...
});
...
});
It's available at
https://www.npmjs.com/package/ng2-mock-component.