首页 > 解决方案 > 如何在构造函数中使用 Jasmine 私有 ActivatedRoute 进行测试?

问题描述

这是我的组件:

@Component({
    selector: 'app-signup',
    templateUrl: './signup.component.html',
    styleUrls: ['./signup.component.scss']
})
export class SignUpComponent implements OnInit {
    specialLink: string;

    constructor(
        private activatedRoute: ActivatedRoute,
    ) {
        this.specialLink = this.activatedRoute.snapshot.params.id;

        if (this.specialLink !== undefined) {
            this.setSpecialSignup();
        }
    }

这是我的测试:

describe('SignUpComponent', () => {
  let component: SignUpComponent;
  let fixture: ComponentFixture<SignUpComponent>;
  let ActivatedRouteMock: any;
  
  beforeEach(async(() => {
    ActivatedRouteMock = jasmine.createSpyObj('ActivatedRoute', ['snapshot']);
    ActivatedRouteMock.snapshot.and.returnValue({ params: { id: "123" } });

    TestBed.configureTestingModule({
      declarations: [ SignUpComponent ],
      imports: [ RouterTestingModule ],
      providers: [
        {provide: ActivatedRoute, useValue: ActivatedRouteMock}
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SignUpComponent);
    component = fixture.componentInstance;
  });

  describe('Function calls', () => {
    beforeEach(() => {
      fixture.detectChanges();
    });

    describe('Patient Side', () => {
   
      it('should call setSpecialSignup() when user is coming from specialLink', () => {
        expect(ActivatedRouteMock.snapshot).toHaveBeenCalled();
      });

我正在尝试测试在我的组件的构造函数中使用的 ActivatedRoute,但出现此错误:TypeError: Cannot read property 'id' of undefined

就像它不识别我的组件中的 ActivatedRoute,而不仅仅是在测试中。

我错过了什么 ?

标签: angulartypescriptrouteskarma-jasmine

解决方案


你嘲笑的方式有点奇怪,为什么不简单地嘲笑一下:

activatedRouteMock: Partial<ActivatedRoute>;

beforeEach(async(() => {
  activatedRouteMock = {
    snapshot: {
      params: { id: 1 }
    } as ActivatedRouteSnapshot,
  };

  TestBed.configureTestingModule({
    declarations: [ SignUpComponent ],
    imports: [ RouterTestingModule ],
    providers: [
      { provide: ActivatedRoute, useValue: activatedRouteMock }
    ]
  })
  .compileComponents();
}));

推荐阅读