Skip to content

Instantly share code, notes, and snippets.

@zladuric
Last active January 15, 2018 09:47
Show Gist options
  • Save zladuric/3901246b0b6d2bc8a422fb443126ee7a to your computer and use it in GitHub Desktop.
Save zladuric/3901246b0b6d2bc8a422fb443126ee7a to your computer and use it in GitHub Desktop.
import { Component, Injectable, Directive, Input, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import {
async,
TestBed,
ComponentFixture
} from '@angular/core/testing';
import { SharedModule } from './shared/shared.module';
import { MaterialModule } from '@angular/material';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
@Injectable()
class MockService {
getThing(id: any) {
console.log('called with id:', id);
return Observable.of({ hi: 'there' });
}
}
@Component({
selector: 'test-component',
template: '<div> this is a test </div>'
})
class TestComponent implements OnInit {
constructor(private activatedRoute: ActivatedRoute, private service: MockService) {}
ngOnInit() {
this.activatedRoute.params.subscribe((params: any) => {
console.log('Hey there, param', params);
this.service.getThing(params.id);
});
}
}
let mockAR: any = {
params: {
subscribe: function() {
console.log('Subscribed.');
Observable.of({ id: 123 });
}
}
}
export function main() {
xdescribe('My Test Component', () => {
let fixture: ComponentFixture<TestComponent>;
let instance: TestComponent;
let domEl: Element;
let routeSpy;
const routes = [
{ path: 'test/:id', component: TestComponent }
];
beforeEach(async(() => {
routeSpy = spyOn(mockAR.params, 'subscribe').and.callThrough();
TestBed.configureTestingModule({
imports: [FormsModule, SharedModule, MaterialModule, RouterTestingModule.withRoutes(routes)],
declarations: [TestComponent],
providers: [
MockService,
{
provide: ActivatedRoute, useValue: mockAR,
}
]
});
TestBed
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(TestComponent);
instance = fixture.debugElement.componentInstance;
domEl = fixture.debugElement.nativeElement;
});
}));
it('should work',
async(() => {
let mockService =
fixture.debugElement.injector.get<any>(MockService) as MockService;
// let serviceSpy = spyOn(mockService, 'getThing').and.callThrough();
fixture.detectChanges();
expect(routeSpy.calls.count()).toBe(1);
// expect(serviceSpy.calls.count()).toBe(1);
}));
});
}
@amormason
Copy link

Error: Can't resolve all parameters for Router: (?, ?, ?, ?, ?, ?, ?, ?).

I have the error message in my angular4 App Testing and I do not know why.

import { Router, ActivatedRoute } from "@angular/router";
import { EnrollMemberModule } from './../enroll-member.module';
import { MembershipService } from './../../../member/services/membership.service';
import { MemberForm } from './../models/enroll-member-form';
import { EnrollMemberPromotionsComponent } from './promotions.component';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { DebugElement,Injectable,Component, OnInit, NgModule, ViewChild } from '@angular/core';
import { ComponentFixtureAutoDetect } from '@angular/core/testing';//自动变更检测
import { async } from '@angular/core/testing';//异步的beforeEach
import { Member } from 'app/member/models/member';
import { FormsModule } from '@angular/forms';
import { ToastrModule } from 'ngx-toastr';
import { Observable, BehaviorSubject } from 'rxjs/Rx';
import { ProformaInvoiceComponent } from 'app/member-prospect-manager/enroll-member/proforma-invoice/proforma-invoice.component';
import { ClubService } from 'app/club/services';
import { HttpModule, Http } from '@angular/http';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { HandleErrorService } from '../../../shared-services/handle-error.service';
import { AccessTypeService } from '../../../club/services/access-type.service';
import { MemberService } from '../../../member/services/member.service';
import { CurrentUserService } from '../../../user/services/current-user.service';
import { GetCurrentUserService } from '../../../user/services/get-current-user.service';
import { PromotionService } from 'app/promotions/services/promotion.service';
import { FormService } from 'app/membership/services/form.service';
import { RouterTestingModule } from "@angular/router/testing";
import {
HomeComponent,
SearchComponent,
AppComponent,
routes
} from "./activated-route"

@Injectable()
class MockService {
getThing(id: any) {
console.log('called with id:', id);
return Observable.of({ hi: 'there' });
}
}

describe('when navigate to promotion selecte', () => {

let component: EnrollMemberPromotionsComponent;
let fixture: ComponentFixture<EnrollMemberPromotionsComponent>;
let de: DebugElement;
let el: HTMLElement;

let location: Location;
let router: Router;
let mockAR: any = {
    params: {
      subscribe: function() {
        console.log('Subscribed.');
        Observable.of({ id: 123 });
      }
    }
  }
class RouterStub {
    navigateByUrl(url: string) { return url; }
}
beforeEach(async () => {
    TestBed.configureTestingModule({
        providers: [
            MockService,
            MembershipService,
            ClubService,
            HandleErrorService,
            AccessTypeService,
            MemberService,
            GetCurrentUserService,
            PromotionService,
            CurrentUserService,
            Router,
            ActivatedRoute,
            FormService,
            { provide: ActivatedRoute, useValue: mockAR, }
        ],
        imports: [
            FormsModule,
            EnrollMemberModule,
            HttpClientModule,
            HttpModule,
            ToastrModule.forRoot(),
            RouterTestingModule.withRoutes(routes)
        ]
    }).compileComponents();  // compile template and css


    router = TestBed.get(Router);
    location = TestBed.get(Location);
    fixture = TestBed.createComponent(EnrollMemberPromotionsComponent);
    router.initialNavigation();
});

beforeEach(() => {
    router = TestBed.get(Router);
    location = TestBed.get(Location);

    component = fixture.componentInstance;
    fixture.detectChanges();
});

it('should create', () => {
    expect(component).toBeTruthy();
});

});

@amormason
Copy link

Can you help me?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment