angular4 测试时 报错Error: Can't resolve all parameters for Router

发布于 2022-09-06 11:08:30 字数 3878 浏览 51 评论 0

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();
});

});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

香橙ぽ 2022-09-13 11:08:31

promotions.component.spec.ts:

import { ClubCodeGuard } from './../../../guards/club-code.guard';
import { EnrollMemberComponent } from './../enroll-member.component';
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 { EnrollMemberMembershipTypeComponent } from 'app/member-prospect-manager/enroll-member/membership-type/membership-type.component';
import { EnrollMemberMembershipInfoComponent } from 'app/member-prospect-manager/enroll-member/membership-info/membership-info.component';
import { EnrollMemberReviewAndPayComponent } from 'app/member-prospect-manager/enroll-member/review-and-pay/review-and-pay.component';
import { EnrollMemberConfirmationComponent } from 'app/member-prospect-manager/enroll-member/confirmation/confirmation.component';

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 });
      }
    }
  }
  let mockRouter = {
    navigate: jasmine.createSpy('navigate')
  } 
beforeEach(async () => {
    TestBed.configureTestingModule({
        providers: [
            MembershipService,
            ClubService,
            HandleErrorService,
            AccessTypeService,
            MemberService,
            GetCurrentUserService,
            PromotionService,
            CurrentUserService,
            Router,
            ActivatedRoute,
            FormService,
            { provide: Router, useValue: mockRouter }
        ],
        imports: [
            FormsModule,
            EnrollMemberModule,
            HttpClientModule,
            HttpModule,
            ToastrModule.forRoot(),
            RouterTestingModule.withRoutes([
                {
                  path: 'tab',
                  component: EnrollMemberComponent,
                  data: {
                    title: 'EnrollMemberComopnent',
                    iconClass: 'fa fa-bullhorn'
                  },
                  canActivate: [ClubCodeGuard],
                  children: [
                    {
                      path: '',
                      redirectTo: 'membership-type',
                      pathMatch: 'full'
                    },
                    {
                      path: 'membership-type',
                      component: EnrollMemberMembershipTypeComponent,
                      data: { title: 'EnrollMemberMembershipTypeComponent', iconClass: 'fa fa-bullhorn' },
                      canActivate: [ClubCodeGuard]
                    },
                    {
                      path: 'membership-info',
                      component: EnrollMemberMembershipInfoComponent,
                      data: { title: 'EnrollMemberMembershipInfoComponent', iconClass: 'fa fa-bullhorn' },
                      canActivate: [ClubCodeGuard]
                    },
                    {
                      path: 'promotions',
                      component: EnrollMemberPromotionsComponent,
                      data: { title: 'EnrollMemberPromotionsComponent', iconClass: 'fa fa-bullhorn' },
                      canActivate: [ClubCodeGuard]
                    },
                    {
                      path: 'review-pay',
                      component: EnrollMemberReviewAndPayComponent,
                      data: { title: 'EnrollMemberReviewAndPayComponent', iconClass: 'fa fa-bullhorn' },
                      canActivate: [ClubCodeGuard]
                    },
                    {
                      path: 'confirmation',
                      component: EnrollMemberConfirmationComponent,
                      data: { title: 'EnrollMemberConfirmationComponent', iconClass: 'fa fa-bullhorn' },
                      canActivate: [ClubCodeGuard]
                    }
                  ]
                },{
                  path: '',
                  redirectTo: 'tab',
                  pathMatch: 'full'
                }
              ])
        ]
    }).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();
});

});

兮颜 2022-09-13 11:08:31

把这行代码

{ provide: Router, useValue: mockRouter }
改成这样:

{ provide: Router, useValue: jasmine.createSpyObj('Router', ['navigate']) },
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文