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

Differences between `typings install` and `@types` installation

Currently, I am in the process of learning how to integrate Angular into an MVC web server. For guidance, I am referring to this tutorial: After some research and noticing a warning from npm, I learned that typings install is no longer used. Instead, it ...

Leverage the same JSDoc comment across multiple TypeScript interfaces

If I have the interfaces below: interface Foo { /** * A date string in the format `yyyy-MM-dd` */ archiveDate: string; } interface Bar { /** * A date string in the format `yyyy-MM-dd` */ publishDate: string; } The JSDoc descriptions f ...

update angular component after deleting an item

After deleting a contact in the table, I'm trying to refresh my contact list page but it's not working. Any suggestions? This is the list of contacts in the contact.component.ts file Swal.fire({ title: 'Do you want to delete this contac ...

Tips for adjusting the width of the box on a BoxPlot chart in Apex charts

Currently, I am utilizing apexcharts(version 3.35.3) within an Angular project and I am looking to adjust the width of the box. After reviewing the documentation for apexcharts, I have not been able to find any specific option that allows me to modify the ...

Refreshing MongoDB data by utilizing values from an object

I am facing a challenge with my MongoDB collection structure: [ { "stock": "GOOGLE", "price": 0 }, { "stock": "FACEBOOK", "price": 0 } ] On the other hand, I have a Stock_P ...

Having trouble sending a JSON object from Typescript to a Web API endpoint via POST request

When attempting to pass a JSON Object from a TypeScript POST call to a Web API method, I have encountered an issue. Fiddler indicates that the object has been successfully converted into JSON with the Content-Type set as 'application/JSON'. Howev ...

Tips for sending an Object within a multipart/form-data request in Angular without the need for converting it to a string

To successfully pass the object in a "multipart/form-data" request for downstream application (Java Spring) to receive it as a List of custom class objects, I am working on handling metadata objects that contain only key and value pairs. Within the Angula ...

Does adding a callback to object.ngOnDestroy() replace its internal onDestroy() method?

I'm enhancing the drag and drop feature in Angular <div cdkDropList appImprovedDropList> <div cdkDrag>item 1</div> <div cdkDrag>item 2</div> <div cdkDrag>item 3</div> </div> The directive appImpro ...

Ways to determine the generic type of a property value from a decorated property within a decorator

While experimenting with some code, I encountered an issue where the generic type of a property value wasn't being resolved correctly when changing from TValue to (t: TValue) => TValue. Instead of being recognized as the expected number, it was now ...

Guide on creating a custom command within the declaration of Tiptap while extending an existing extension with TypeScript

I'm currently working on extending a table extension from tiptap and incorporating an additional command. declare module '@tiptap/core' { interface Commands<ReturnType> { table: { setTableClassName: () => ReturnType; ...

Launching ngx-modal in Angular2 without the need for a button click

As a newcomer to Angular2, I am seeking guidance on how to trigger an alert Modal in the event of a failed login within my code. While most examples I have come across rely on a button click, I am wondering if it is possible to achieve this based on the st ...

Issue with PrimeNG DataTable contextMenu alignment inside TabView

I encountered an issue with displaying a DataTable - contextMenu when it is placed within a TabView. The contextMenu was appearing off-center. However, the DataTable - contextMenu worked perfectly fine when it was not wrapped in a TabView. To address this ...

Error in React Native Typescript: The type 'string' cannot be assigned to the type '"solid" | "clear" | "outline"'. (Error code: ts(2322))

I have integrated TypeScript with React Native in my project. import React from 'react'; import { Button } from 'react-native-elements'; import { IThemedButton } from '../../../models/themedButton'; interface IThemedButtonPr ...

Tips for customizing the list of components and attributes for each component in the Angular Form.io builder

I have successfully integrated form.io with Angular 10. After creating a demo project using form.io in the Angular CLI, I was able to develop a custom component and customize the editForm for it. import { Injector } from '@angular/core'; import ...

Updating meta tags dynamically in Angular Universal with content changes

Hello, I'm encountering an issue with a dynamic blog page. I am trying to update meta tags using data fetched from the page. Here's the code snippet: getBlogPost() { this.http.get(...) .subscribe(result => { this.blogPost = re ...

Enhance User Experience - Automatically highlight the first element in Prime NG Menu when activated

I have been working on transitioning the focus from the PrimeNG menu to the first element in the list when the menu is toggled. Here is what I've come up with: In my template, I added: <p-menu appendTo="body" #menu [popup]="true&quo ...

Connect a click event from one component to another component

Can Angular bind a click event dynamically from a component to another existing component on the page? Check out this image for reference. In my app, I have 4 simple components - a shell component that defines the layout, a header component (blue outline) ...

What is the best way to eliminate a particular element from an array produced using the .map() function in

I am experiencing an issue with my EventCell.tsx component. When a user clicks on the component, an event is created by adding an element to the components state. Subsequently, a list of Event.tsx components is rendered using the .map() method. The problem ...

You are unable to apply 'use client' on a layout element in Next.js

While attempting to retrieve the current page from the layout.txt file, I encountered errors after adding 'use client' at the top of the page: Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data parseMod ...

Encountering a problem with an InvalidPipeArgument in Angular 6

Here's a quick summary of the situation: I recently upgraded my application to the latest version of Angular, moving from 5 to 6. All deployments in the packages.json file were updated using the ng update command. In my application, I save a Date() ...