Jasmine's await function often leads to variables remaining undefined

When testing a function, I encountered an issue where a variable is created and assigned a value, but the payload constant always remains undefined.

campaigns-card.component.ts

async ngOnInit() {
    const { uid } = await this.auth.currentUser
    const { payload } = await this.firestore.surveysUsers(this.survey.id).doc(uid).snapshotChanges().pipe(first()).toPromise();
    this.completed = payload.exists
  }

component-card.component.spec.ts

beforeEach(waitForAsync(() => {
    fireStoreServiceMock.surveysUsers.and.returnValue({ 
      doc: () => { return {
        snapshotChanges: () => { return {
          pipe: () => { return {
            toPromise: () => { return { exists: true }}
          }}
        }}
      }}
    });
  }));

describe('tests in delete', () => {
    it('should update surveys', fakeAsync(() => {
      fixture.detectChanges();
      component.delete().then(() => {
      });
      fixture.detectChanges();
      tick();

      expect(fireStoreServiceMock.surveys).toHaveBeenCalled();
      expect(snackBarMock.open).toHaveBeenCalled();
    }));
  });

Error Message:

Error: Uncaught (in promise): TypeError: Cannot read property 'exists' of undefined
TypeError: Cannot read property 'exists' of undefined
    at CampaignsCardComponent.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/src/app/modules/campaigns/pages/campaigns-card/campaigns-card.component.ts:43:4)
    <Rest of error stack trace>

Answer №1

Close to the solution. The issue lies in treating this as an observable and attempting to mock the pipe function, whereas you should be returning an observable from the function.

Consider this approach:

import { of } from 'rxjs';
....
beforeEach(waitForAsync(() => {
    fireStoreServiceMock.surveysUsers.and.returnValue({ 
      doc: () => { return {
        snapshotChanges: () => of({ exists: true }) // simulate the observable with of
        }}
      }}
    });
  }));

It's possible that there were some discrepancies involving brackets ({ }), but that modification should resolve the issue.

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

The issue with ngx-bootstrap-modal is that it fails to interpret HTML elements

In my Angular 5 project, I am implementing ngx-bootstrap-modal. Below is the code I am using to open the modal: this.dialogService.addDialog(PopUpComponent, { title: 'Custom locale', message: "Hello ? " }).subscribe((isConfirmed ...

The element 'mat-tab' does not recognize the property 'active', therefore it cannot be bound

I keep encountering this error even though I have already imported MatTabsModule. Below is the structure of my component: @Component({ selector: 'app-settings-page', template: ` <mat-tab-group animationDuration="0ms"> <mat-tab *n ...

Having trouble implementing ng2-charts in Angular 4 when using shared components

Using angular 4.0.0, angular-cli 1.2.1, and ng2-charts 1.6.0 has been a smooth experience for me so far. However, I encountered an issue when trying to incorporate ng2-charts into "shared" components. In my setup, I have a shared-components.module that is ...

The Nuxt content Type 'ParsedContent | null' cannot be assigned to type 'Record<string, any> | undefined'

I've been experimenting with @nuxt/content but I'm struggling to create a functional demo using a basic example. ERROR(vue-tsc) Type 'ParsedContent | null' is not assignable to type 'Record<string, any> | undefined'. ...

Angular 2 - Beginner's guide to updating the header when navigating to a new route or page

SOLVED I am faced with a challenge involving multiple components in Angular2. Specifically, I have the following components: home component, default header, detail component, and detail header component. Each header has a unique layout. At the Home pa ...

Error: Unexpected character U found at the beginning of the JSON data when using JSON.parse in Angular 8

Lately, I came across an issue while making changes to some parts of my previous code. The error caught my attention as it occurred when trying to pass a specific object or a part of that object in Angular 8, NodeJS with express, and mongoose. Upon checki ...

When I attempt to map imports in Typescript, an error occurs, stating, "Element implicitly has an 'any' type because the expression of type 'string' is being indexed into type 'typeof import'."

(parameter) key: string An issue arises where the expression of type 'string' cannot be used to index type 'typeof import("d:/Projects/Front/attendance-checker2/src/redux/modules/sagas")', leading to an implicit 'any&a ...

Tips for defining a data structure that captures the type of keys and values associated with an object

Is there a way for the compiler to verify the type of value in this scenario? type SomeType = { foo: string[]; bar: number | null; }; type SomeTypeChanges<K extends keyof SomeType = keyof SomeType> = { key: K; value: SomeType[K] }; declare ...

Looking to programmatically define the locale for Kendo-Ui-Datepicker element

We have integrated a locale service into our existing Angular application, which sets the locale based on a dropdown selection. This locale service is part of the angular-l10n library. After acquiring Kendo-UI for Angular, we were hoping to connect the da ...

How to access the component instance in Angular through router events

I am currently working on incorporating a title service into my Angular 10 application. My goal is to subscribe to router events, access the activated route's component, check if it has a title() getter, and then use that information to set the page&a ...

Replace Nebular theme with a new design for a single component

I am currently using Nebular in my Angular application and I am trying to figure out how to customize the theme settings for a specific component on just one page, without affecting other instances of the same component that are using the default settings. ...

Adding an item into a list with TypeScript is as simple as inserting it in the correct

I am working with a list and want to insert something between items. I found a way to do it using the reduce method in JavaScript: const arr = [1, 2, 3]; arr.reduce((all, cur) => [ ...(all instanceof Array ? all : [all]), 0, cur ]) During the fir ...

Observable emitting value after execution of method

Why does the getModel() method always return an array with empty name arrays even when the languages Observable returns a value? export interface Category extends BaseModel { code: string; name: LocalizedValue[]; description: Local ...

Vue's computed property utilizing typed variables

I am trying to create a computed array of type Todo[], but I keep encountering this specific error: No overload matches this call. Overload 1 of 2, '(getter: ComputedGetter<Todo[]>, debugOptions?: DebuggerOptions | undefined): ComputedRef<T ...

Mastering the art of Promises and handling errors

I've been tasked with developing a WebApp using Angular, but I'm facing a challenge as the project involves Typescript and asynchronous programming, which are new to me. The prototype already exists, and it includes a handshake process that consi ...

Disabling `no-dupe-keys` in ESLint does not seem to be effective

Currently, I am working on a project where I have incorporated Typescript and ESLint. However, I have encountered an issue with the error message stating: An object literal cannot have multiple properties with the same name. I am looking to disable this s ...

The state is accurate despite receiving null as the return value

I'm feeling a bit lost here. I have a main component that is subscribing to and fetching data (I'm using the redux dev tools to monitor it and it's updating the state as needed). In component A, I am doing: public FDC$ = this.store.pipe(sel ...

Retrieving Values from Components in Angular 6

Encountering an issue while retrieving values from different components. The scenario involves 2 components - ReceiveBookingManageComponent as the first component and DriverTablePickerComponent as the second one. The problem arises in DriverTablePickerCo ...

Various modules in the project need to have distinct GitHub origins, particularly in the case of Spring-Angular

My goal is to create a well-structured project with separate frontend and backend modules. Here is the initial project structure: https://i.stack.imgur.com/EghPA.png I have attempted this in various configurations before, but every time I try, git recogn ...

Does the ngOnInit() method get called every time a Page is navigated to in Ionic 4 using navCtrl.navigateRoot()?

I've been trying to locate the official Ionic 4 Documentation regarding the new Ionic NavController, specifically in relation to whether or not ngOnInit() will consistently be called on the Ionic Page component we navigate to when using navCtrl.naviga ...