Is there a way for a function to be executed without being detected by surveillance?

Here's the Component I'm working with:

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

Now, let's take a look at my test cases:

describe('SignUpComponent Testing', () => {
  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('Testing for Special Link', () => {
      it('should call setSpecialSignup() method when user is coming from specialLink', () => {
        spyOn(ActivatedRouteMock, 'snapshot');
        console.log('Test2', component.specialLink)
        expect(ActivatedRouteMock.snapshot).toHaveBeenCalled();
    });

I have verified that activatedRoute has been called correctly. The two 'console.log' statements confirm this by displaying the correct value (123). So why am I encountering this error message:

Expected spy snapshot to have been called
? What could be causing this discrepancy?

Answer №1

Trying to spy on the snapshot variable won't work because it is not a function or method; you can only spy on functions/methods and expect them to be called. It appears that snapshot is an object, so you'll need to adjust your assertion.

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

This test may not fully evaluate functionality, but it demonstrates how I would handle the assertion in this case.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Assuming control value accessor - redirecting attention

import { Component, Input, forwardRef, OnChanges } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; @Component({ selector: 'formatted-currency-input', templateUrl: '../v ...

Encountering an issue with the form onSubmit function in React TypeScript due to an incorrect type declaration

I have a function below that needs to be passed into another component with the correct type definition for updateChannelInfo, but I am encountering an issue with the type showing incorrectly: const updateChannelInfo = (event: React.FormEvent<HTMLFormEl ...

What is the best way to enable code sharing between two TypeScript projects housed within the same repository?

Our project has the following structure: api (dir) -- package.json -- tsconfig.json -- src (dir) -- client (dir) ---- package.json ---- tsconfig.json ---- src (dir) The "client" directory houses a create-react-app project that proxies to the API d ...

The address :::3000 is already in use by NestJS

While attempting to deploy my NestJs server on a C-Panel hosting, I have encountered an issue. Despite properly installing all node_modules and ensuring every project file is in place, the server fails to start and continuously displays the following error ...

Encountering a problem with Typescript and eslint while utilizing styled-components and Material UI: "Warning: React does not identify the `showText` prop on a DOM element."

While using a styled component to return a material ui Fab component, an error appears in the console: React does not recognize the `showText` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as low ...

Angular2 form builder generating dynamic forms based on results of asynchronous calls

When creating my form, I encountered a challenge with passing the results of an asynchronous call to the form builder. This is what I have attempted: export class PerformInspectionPage implements OnInit { checklists: any; inspectionform: FormGroup; n ...

What is the reason for Angular HttpClient to substitute " " with "↵"?

When using the HttpClient to send a POST body that is either a string or an object with a string value, any instances of "\n" are being replaced with "↵", especially in Chrome 73. Interestingly, in Firefox, it seems like "↵" is displayed as " " wh ...

Exploring the power of Angular and Module Federation in SSR applications

Currently, I am utilizing angular version 13.1.0 and have successfully set up SSR by using the ng add @nguniversal/common command. In addition to that, I integrated module federation through ng add @angular-architects/<a href="/cdn-cgi/l/email-protectio ...

Validator in Angular FormControl ensures that two fields have the same value or both are empty

When filling out a form with four fields, I have encountered a specific requirement. Two of the fields are mandatory, which is straightforward. However, the other two must either both be empty or both have a value - essentially resembling an XNOR logic sta ...

Creating a conditional class property requirement in TypeScriptAnother way to implement conditionally required class

I am currently in the process of creating an Event class with a data property that is typed based on the type of the event. Here is the code snippet I have been working on: export interface EventTypes { localeChange: { locale: string; }; translat ...

The proper method for retrieving FormData using SyntheticEvent

I recently implemented a solution to submit form data using React forms with the onSubmit event handler. I passed the SyntheticBaseEvent object to a function called handleSubmit where I manually extracted its values. I have identified the specific data I n ...

Mockery Madness - Exploring the art of mocking a function post-testing a route

Before mocking the process function within the GatewayImpl class to return the 'mockData' payload, I need to ensure that all routes are tested. import payload from './payloads/payloadRequire'; // payload for request import {Gate ...

Extract JSON values based on a given condition

I am working on a Typescript project that involves an array and a JSON object. I need to extract the value of a property from the object based on another property's value being in the array. Here is the array: let country: string[] = [ 'AR' ...

The modal popup will be triggered by various button clicks, each displaying slightly different data within the popup

As a newcomer to Angular 4, I have encountered an interesting challenge. Currently, my code consists of two separate components for two different modals triggered by two different button clicks (Add User and Edit User). However, I now face the requiremen ...

Do constructors in TypeScript automatically replace the value of `this` with the object returned when using `super(...)`?

I’m having some trouble grasping a concept from the documentation: According to ES2015, constructors that return an object will automatically replace the value of “this” for any instances where “super(…)” is called. The constructor code must ...

Tips for designing a personalized payment page in PayPal for flexible one-time and subscription-based payments

How can I display a PayPal checkout page with custom fields such as tax and total amount when a user makes a payment for a custom amount? Can multiple fields like sales tax and total amount be added? In addition to that, our web application already has Pa ...

Why does FormGroup.Get() return null when there is a period in the name of the FormControl?

Issue: I am facing an issue with the formGroup I created using formbuilder. The problem arises when a control within the FormGroup contains a . in its name. When attempting to retrieve the formControl using the formGroup.get method, it returns null. Sampl ...

Adding cache to Observable in mat-autocomplete can improve performance by reducing redundant API calls

I have successfully implemented a mat-autocomplete feature. However, I am facing an issue where the Http call is triggered with every keyup event, such as 'r', 'ra', 'ram', 'rame', 'ramesh'. This frequent u ...

The object instance is failing to receive the Angular Injected service assignment

I am currently utilizing Angular6 and have the following code: 'use strict'; import {ChangeDetectorRef, Component, OnInit} from '@angular/core'; import {MainService} from "./services/main.service"; import {AppService} from "../../app. ...

I am encountering a problem with my Material UI react-swipeable-views while using TypeScript

It seems that there is a mismatch in the version of some components. import * as React from "react"; import { useTheme } from "@mui/material/styles"; import Box from "@mui/material/Box"; import MobileStepper from "@mui/ma ...