cuzureau
cuzureau

Reputation: 380

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

Here's my Component :

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

And here's my tests :

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

I'm testing if activatedRoute has been called. And it is ! The 2 'console.log' prove it since they print the correct value (123). Then, why do I get this error : Expected spy snapshot to have been called.? What did I miss ?

Upvotes: 0

Views: 40

Answers (1)

AliF50
AliF50

Reputation: 18839

You can't spy on snapshot since it is not a function/method, you can only spy on a function/method and expect it to be called. Snapshot seems to be an object. You have to change your assertion.

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

This, however, is not a great test that tests functionality but that's how I would do the assertion if I were you.

Upvotes: 2

Related Questions