Angular2 Inject ElementRef in unit test - unit-testing

I am trying to test a component that receives a reference to ElementRef through DI.
import { Component, OnInit, ElementRef } from '#angular/core';
#Component({
selector: 'cp',
templateUrl: '...',
styleUrls: ['...']
})
export class MyComponent implements OnInit {
constructor(private elementRef: ElementRef) {
//stuffs
}
ngAfterViewInit() {
// things
}
ngOnInit() {
}
}
and the test:
import {
beforeEach,
beforeEachProviders,
describe,
expect,
it,
inject,
} from '#angular/core/testing';
import { ComponentFixture, TestComponentBuilder } from '#angular/compiler/testing';
import { Component, Renderer, ElementRef } from '#angular/core';
import { By } from '#angular/platform-browser';
describe('Component: My', () => {
let builder: TestComponentBuilder;
beforeEachProviders(() => [MyComponent]);
beforeEach(inject([TestComponentBuilder], function (tcb: TestComponentBuilder) {
builder = tcb;
}));
it('should inject the component', inject([MyComponent],
(component: MyComponent) => {
expect(component).toBeTruthy();
}));
it('should create the component', inject([], () => {
return builder.createAsync(MyComponentTestController)
.then((fixture: ComponentFixture<any>) => {
let query = fixture.debugElement.query(By.directive(MyComponent));
expect(query).toBeTruthy();
expect(query.componentInstance).toBeTruthy();
});
}));
});
#Component({
selector: 'test',
template: `
<cp></cp>
`,
directives: [MyComponent]
})
class MyTestController {
}
Both the component and the test blueprint have been generated by Angular-cli. Now, I can't figure out which provider, if any, I should add in the beforeEachProviders for the injection of ElementRef to be successful. When I run ng test I got Error: No provider for ElementRef! (MyComponent -> ElementRef).

I encounter Can't resolve all parameters for ElementRef: (?) Error using the mock from #gilad-s in angular 2.4
Modified the mock class to:
export class MockElementRef extends ElementRef {
constructor() { super(null); }
}
resolves the test error.
Reading from the angular source code here: https://github.com/angular/angular/blob/master/packages/core/testing/src/component_fixture.ts#L17-L60
the elementRef of the fixture is not created from the mock injection. And in normal development, we do not explicitly provide ElementRef when injecting to a component. I think TestBed should allow the same behaviour.

On Angular 2.2.3:
export class MockElementRef extends ElementRef {}
Then in the test:
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
//more providers
{ provide: ElementRef, useClass: MockElementRef }
]
}).compileComponents();
}));

To inject an ElementRef:
Create a mock
class MockElementRef implements ElementRef {
nativeElement = {};
}
Provide the mock to the component under test
beforeEachProviders(() => [Component, provide(ElementRef, { useValue: new MockElementRef() })]);
EDIT: This was working on rc4. Final release introduced breaking changes and invalidates this answer.

A good way is to use spyOn and spyOnProperty to instant mock the methods and properties as needed. spyOnProperty expects 3 properties and you need to pass get or set as third property. spyOn works with class and method and returns required value.
Example
const div = fixture.debugElement.query(By.css('.ellipsis-overflow'));
// now mock properties
spyOnProperty(div.nativeElement, 'clientWidth', 'get').and.returnValue(1400);
spyOnProperty(div.nativeElement, 'scrollWidth', 'get').and.returnValue(2400);
Here I am setting the get of clientWidth of div.nativeElement object.

It started showing up after I did a package update in my Angular project.
I tried all the solutions above and none of them worked for me. The problem occurred when I ran the npm run test command.
I managed to solve by updating all jest dependencies. In this case, the dependencies I updated were #briebug/jest-schematic, #types/jest, jest-preset-angular and jest

Related

Setting up a Test Bed in Ionic Provider

I am really new into Ionic and Unit Testing. Current version is 3.12.0. I am using Karma and Jasmine for unit testing.
I have a provider called test-service.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the TestServiceProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
#Injectable()
export class TestServiceProvider {
constructor(public http: Http) {
console.log('Hello TestServiceProvider Provider');
}
}
Then I have a test spec in the same folder as follows contains a simple test with a test bed.
import { TestServiceProvider } from './test-service';
import { TestBed, TestModuleMetadata, async, ComponentFixture } from '#angular/core/testing';
describe('Test Service', () => {
let component: TestServiceProvider;
let fixture: ComponentFixture<TestServiceProvider>;
beforeEach(async( () => {
TestBed.configureTestingModule({
imports: [TestServiceProvider]
}).compileComponents;
}));
beforeEach( () => {
fixture = TestBed.createComponent(TestServiceProvider);
component = fixture.componentInstance;
});
it('should add numbers', () => {
expect(1+1).toBe(2);
});
});
But when I run npm test it gives me an error
Unexpected value 'TestServiceProvider' imported by the module 'DynamicTestModule'. Please add a #NgModule annotation.
What am I doing wrong here and how do I fix this?
TestServiceProvider must be in the declaration not in Imports
Change Your code as below :
beforeEach(async( () => {
TestBed.configureTestingModule({
declarations: [TestServiceProvider]
}).compileComponents;
}));

Testing a component with dependencies using karma & jasmine

I'm new to angular 2 and I have some problems testing my code. I use the jasmine testing framework and the karma test runner to test my app.
I have a component (called GroupDetailsComponent) that I want to test. This component uses two services (GroupService & TagelerServie, both have CRUD methods to talk to an API) and some pipes in the html file. My component looks like this:
import 'rxjs/add/operator/switchMap';
import { Component, Input, OnInit } from '#angular/core';
import { Tageler } from '../../tagelers/tageler';
import { TagelerService } from '../../tagelers/tageler.service';
import { Params, ActivatedRoute } from '#angular/router';
import { GroupService} from "../group.service";
import { Group } from '../group';
#Component({
selector: 'app-group-details',
templateUrl: 'group-details.component.html',
styleUrls: ['group-details.component.css'],
})
export class GroupDetailsComponent implements OnInit {
#Input()
tageler: Tageler;
tagelers: Tageler[];
group: Group;
constructor(
private route: ActivatedRoute,
private groupService: GroupService,
private tagelerService: TagelerService) {
}
ngOnInit() {
console.log("Init Details");
this.route.params
.switchMap((params: Params) => this.groupService.getGroup(params['id']))
.subscribe(group => this.group = group);
this.tagelerService
.getTagelers()
.then((tagelers: Tageler[]) => {
// some code
}
return tageler;
});
});
}
}
And the test file looks like this:
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { GroupDetailsComponent } from './group-details.component';
import { FilterTagelerByGroupPipe } from '../../pipes/filterTagelerByGroup.pipe';
import { SameDateTagelerPipe } from '../../pipes/sameDateTageler.pipe';
import { CurrentTagelerPipe } from '../../pipes/currentTageler.pipe';
import { NextTagelerPipe } from '../../pipes/nextTageler.pipe';
import { RouterTestingModule } from '#angular/router/testing';
import { GroupService } from '../group.service';
import { TagelerService } from '../../tagelers/tageler.service';
describe('GroupDetailsComponent', () => {
let component: GroupDetailsComponent;
let fixture: ComponentFixture<GroupDetailsComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
GroupDetailsComponent,
FilterTagelerByGroupPipe,
SameDateTagelerPipe,
CurrentTagelerPipe,
NextTagelerPipe, ],
imports: [ RouterTestingModule ],
providers: [{provide: GroupService}, {provide: TagelerService}],
})
fixture = TestBed.createComponent(GroupDetailsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
class MockGroupService {
getGroups(): Array<Group> {
let toReturn: Array<Group> = [];
toReturn.push(new Group('Trupp', 'Gruppe 1'));
return toReturn;
};
}
it('should create component', () => {
expect(component).toBeDefined();
});
});
I read the angular 2 documentation about testing and a lot of blogs, but I still don't really understand how to test a component that uses services and pipes. When I start the test runner, the test 'should create component' fails and I get the message that my component is not defined (but I don't understand why). I also don't understand how I have to inject the services and pipes. How do I mock them the right way?
I hope that someone can give me helpful advice!
Ramona
You can use spyOn to fake the call in jasmine.
spyOn(yourService, 'method').and.returnValue($q.resolve(yourState));

Unit Testing No provider for ChangeDetectorRef

version: Angular 4.
I am injecting a parent component into child component to access parent method through child component.
In parent-component I had to use ChangeDetectorRef because it has a property which will update runtime.
Now code is working fine but child-component spec is throwing error for "ChangeDetectorRef" which is injected in parent component.
Error: No provider for ChangeDetectorRef!
Parent Component
import { Component, AfterViewChecked, ChangeDetectorRef, ChangeDetectionStrategy } from '#angular/core';
#Component({
selector: 'parent-component',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ParentComponent implements AfterViewChecked {
stageWidth: number;
constructor(private ref: ChangeDetectorRef) {
this.ref = ref;
}
//call this function as many times as number of child components within parent-component.
parentMethod(childInterface: ChildInterface) {
this.childInterfaces.push(childInterface);
}
ngAfterViewChecked() {
this.elementWidth = this.updateElementWidthRuntime();
this.ref.detectChanges();
}
}
Child Component
import { Component, AfterViewInit } from '#angular/core';
import { ParentComponent } from '../carousel.component';
#Component({
selector: 'child-component',
templateUrl: './carousel-slide.component.html',
styleUrls: ['./carousel-slide.component.scss'],
})
export class ChildComponent implements AfterViewInit {
constructor(private parentComponent: ParentComponent) {
}
ngAfterViewInit() {
this.parentComponent.parentMethod(this);
}
}
app.html
<parent-component>
<child-component>
<div class="box">Content of any height and width</div>
</child-component>
<child-component>
<div class="box">Content of any height and width</div>
</child-component>
<child-component>
<div class="box">Content of any height and width</div>
</child-component>
</parent-component>
Unit test for Child Component
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { ParentComponent } from '../parent.component';
import { ChildComponent } from './child.component';
describe('ChildComponent', () => {
let component: ChildComponent;
let fixture: ComponentFixture<ChildComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ChildComponent],
providers: [ParentComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ChildComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create \'ChildComponent\'', () => {
expect(component).toBeTruthy();
});
});
When I am trying to add ChangeDetectorRef in providers in child spec, I am getting following error.
Failed: Encountered undefined provider! Usually this means you have a
circular dependencies (might be caused by using 'barrel' index.ts
files.)
After googling and trying many things I am unable to find solution. Any help appreciated.
You are using a component as a provider, which is probably not your intention. Change your test module to declare both your parent and child components.
TestBed.configureTestingModule({
declarations: [ChildComponent, ParentComponent],
providers: []
})
I am able to get rid of this error by making "ChangeDetectorRef" as #Optional dependency in my Parent Component.
constructor(#Optional() private ref: ChangeDetectorRef) {
this.ref = ref;
}
This way my child component's configureTestingModule will ignore ParentComponent provider.

Angular 2.0.0 - Mock File Uploader

I am using ng2-file-upload. How do I mock its FileUploader class in unit testing?
import { FileUploader } from 'ng2-file-upload/ng2-file-upload';
#Component({
selector: 'my-component',
template: '...',
providers: [ MyService ]
})
export class MyComponent {
public uploader: FileUploader = new FileUploader({url: '/my-app/api/upload',
authToken: 'token'});
constructor() {
this.uploader.onCompleteItem = (item:any, response: any, headers: any) => {
console.log('how to test here');
}
}
I am having a hard time mocking it in my spec. Please help.
I was going to reply to your comment, but I think the following may help to answer your original question on how to mock the FileUploader class taken from their unit test from the file file-drop.directive.spec.ts:
import { Component } from '#angular/core';
import { inject, ComponentFixture, TestBed } from '#angular/core/testing';
import { FileUploader } from './file-uploader.class';
import { FileUploadModule } from './file-upload.module';
#Component({
selector: 'container',
template: `<input type="file" ng2FileSelect [uploader]="uploader" />`
})
export class ContainerComponent {
public uploader:FileUploader = new FileUploader({url: 'localhost:3000'});
}
describe('Directive: FileSelectDirective', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FileUploadModule],
declarations: [ContainerComponent],
providers: [ContainerComponent]
});
});
it('should be fine', inject([ContainerComponent], (fixture:ComponentFixture<ContainerComponent>) => {
expect(fixture).not.toBeNull();
}));
});
Where import { FileUploader } from './file-uploader.class'; is how you import the FileUploader into your test, ContainerComponent is imported into the test itself.
Further to this, I have created a dummy file to test with on my component, but I am still writing it!
it('should accept a file for upload', () => {
var modifiedDate = new Date();
var file = new File([3555], 'test-file.jpg', {lastModified : modifiedDate, type: 'image/jpeg'});
FileUploadComponent.upload(file);
});
To test if this works, I have a metadata model that I expect to be populated upon the file being selected. I can therefore make two assertions, that both the upload input box will have a file and that the metadata object will be populated.
In the case of ng2-file-upload, I beleive the file list will be populated allowing you to check that the test file has been imported into that.
Good luck!

Angular 2 RC4: Unit test component that has dependency injection a service that has its own

As Angular team is constantly upgrading/deprecating stuff in Angular 2 RC versions I encountered this problem.
I have a component that has a Dependency Injection (DI), which is actually a service (UserService in this case). This UserService of course has some DIs of its own. After updating to the latest RC4 of Angular 2 I realised that I cannot create similar tests any more.
So as the docs are not mentioning something relative here's my code (simplified for this question).
My component:
import { Component } from '#angular/core';
import { MdButton } from '#angular2-material/button';
import {
MdIcon,
MdIconRegistry
} from '#angular2-material/icon';
import { UserService } from '../../services/index';
#Component({
moduleId: module.id,
selector: 'logout-button',
templateUrl: 'logout-button.component.html',
styleUrls: ['logout-button.component.css'],
providers: [MdIconRegistry, UserService],
directives: [MdButton, MdIcon]
})
export class LogoutButtonComponent {
constructor(public userService: UserService) {}
/**
* Call UserService and logout() method
*/
logout() {
this.userService.logout();
}
}
Component's DI, UserService whic as you can see has some DIs (Router, AuthHttp & Http):
import { Injectable } from '#angular/core';
import {
Http,
Headers
} from '#angular/http';
import {
AuthHttp,
JwtHelper
} from 'angular2-jwt';
import { Router } from '#angular/router';
import { UMS } from '../common/index';
#Injectable()
export class UserService {
constructor(
private router: Router,
private authHttp: AuthHttp,
private http: Http) {
this.router = router;
this.authHttp = authHttp;
this.http = http;
}
/**
* Logs out user
*/
public logout() {
this.authHttp.get(UMS.url + UMS.apis.logout)
.subscribe(
data => this.logoutSuccess(),
err => this.logoutSuccess()
);
}
}
And here's the test for the component:
import { By } from '#angular/platform-browser';
import { DebugElement } from '#angular/core';
import {
beforeEach,
beforeEachProviders,
describe,
expect,
it,
inject,
fakeAsync,
TestComponentBuilder
} from '#angular/core/testing';
import { AuthHttp } from 'angular2-jwt';
import { Router } from '#angular/router';
import { Http } from '#angular/http';
import { LogoutButtonComponent } from './logout-button.component';
import { UserService } from '../../services/index';
describe('Component: LogoutButtonComponent', () => {
beforeEachProviders(() => [
LogoutButtonComponent,
UserService
]);
it('should inject UserService', inject([LogoutButtonComponent],
(component: LogoutButtonComponent) => {
expect(component).toBeTruthy();
}));
});
Don't worry about the (it) for now.
As you can see I;m adding the related providers on the beforeEachProviders.
In this case I'm getting an error when I run the tests:
Error: No provider for Router! (LogoutButtonComponent -> UserService -> Router)
Which is expected let's say.
So in order to don't get those errors I'm adding the service's DIs in the providers also:
beforeEachProviders(() => [
LogoutButtonComponent,
Router,
AuthHttp,
Http,
UserService
]);
But now I'm, getting this error:
Error: Cannot resolve all parameters for 'Router'(?, ?, ?, ?, ?, ?, ?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'Router' is decorated with Injectable.
I'm really trying to figure out what's happening so I found some related answers here but ALL are outdated and covers the old router-deprecated or angular2/router but both are deprecated and are not covering this case.
Would love some help on this and maybe some resources as I cannot find anything related to the latest version of Router: "#angular/router": "3.0.0-beta.2", and RC4.
Thanks
UPDATE!
I manage to bypass the two errors above and now I can access the component. Here's the description code:
describe('Component: LogoutButtonComponent', () => {
let component: LogoutButtonComponent;
let router: any = Router;
let authHttp: any = AuthHttp;
let http: any = Http;
let service: any = new UserService(router, authHttp, http);
beforeEachProviders(() => [
LogoutButtonComponent
]);
beforeEach(() => {
component = new LogoutButtonComponent(service);
});
it('should inject UserService', () => {
expect(component.userService).toBeTruthy();
});
it('should logout user', () => {
localStorage.setItem('token', 'FOO');
component.logout();
expect(localStorage.getItem('token')).toBeUndefined();
});
});
But it seems that even that the DI service is injected and accessible the DIs of the service are not. So now I get this error:
TypeError: this.authHttp.get is not a function
Any ideas?
It looks like you were experiencing a dependencies loop problem, because your UserSerivce also need inject AuthHttp, Http, etc... it really will be disturb once if you need test your component.
My way is just create a mock UserSerivce and return the expect mocked value through UserService.logout() method, because you don't have to know what really happened in UserService, all you need is just a return value:
let MockUserService = {
logout() {
// return some value you need
}
}
Then, in test suite:
import { provide } from '#angular/core'
beforeEachProviders(() => [
provide(UserService, {useClass: MockUserService})
])
... detail test code here
I hope this works for you.
And here is a post that helps me a lot:
https://developers.livechatinc.com/blog/testing-angular-2-apps-dependency-injection-and-components/
With RC4, some workarounds are needed to use http in a test. See also this issue (should be fixed in RC5):
https://github.com/angular/angular/issues/9294
Adding this to my unit-tests.html fixed it for me:
System.import('#angular/platform-browser/src/browser/browser_adapter').then(function(browser_adapter) {
browser_adapter.BrowserDomAdapter.makeCurrent();
})