如何调用函数而不被间谍检测到?

How can a function be called and not be detected by spy?

这是我的组件:

@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;
        console.log('TEST1', this.specialLink);
    }

这是我的测试:

describe('SignUpComponent', () => {
  let component: SignUpComponent;
  let fixture: ComponentFixture<SignUpComponent>;
  let ActivatedRouteMock: any;
  
  beforeEach(async(() => {
    ActivatedRouteMock = {
      snapshot: {
        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', () => {
        spyOn(ActivatedRouteMock, 'snapshot');
        console.log('Test2', component.specialLink)
        expect(ActivatedRouteMock.snapshot).toHaveBeenCalled();
    });

我正在测试是否已调用 activatedRoute。它是! 2 'console.log' 证明了这一点,因为它们打印了正确的值 (123)。那么,为什么会出现此错误:Expected spy snapshot to have been called.? 我错过了什么?

您不能监视 snapshot,因为它不是 function/method,您只能监视 function/method 并期望它被调用。快照似乎是一个对象。你必须改变你的主张。

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

然而,这不是测试功能的好测试,但如果我是你,我会这样做。