experimenting with asynchronous promises in Jasmine to test Angular 2 services

Currently, I'm facing some challenges while testing my Angular 2 service. Even though my tests are passing, I keep encountering this error in the console:

context.js:243 Unhandled Promise rejection: 'expect' was used when there was no current spec; this could be due to an asynchronous test timing out ; Zone: ProxyZone ; Task: Promise.then ; Value: Error: 'expect' was used when there was no current spec; this could be because an asynchronous test timed out

The service I am working on utilizes PouchDB and returns a promise.

Here is a snippet of my service code:

import { Injectable } from '@angular/core';
import { Project } from './project';
declare var PouchDB:any;

@Injectable()
export class ProjectService {

  db: any;

  constructor() {
    if(navigator.vendor && navigator.vendor.indexOf('Apple') > -1){
      this.db = new PouchDB('projects', {adapter: 'fruitdown'});
    }else{
      this.db = new PouchDB('projects');
    }   
  }

  saveProject(project:Project): Promise<any>{
    return this.db.put(project);
  }

  getProjects(limit:number,skip:number): Promise<any> {
    return this.db.allDocs({
      include_docs: true,
      attachments: false,
      descending: true,
      limit: limit,
      skip: skip
    });
  }

}

Below is an excerpt from my test specification:

import { TestBed, inject, async } from '@angular/core/testing';

import { Project, ProjectService } from './index';

describe('ProjectService', () => {

  let project: Project;
  let service: ProjectService;

  let createFakeProject = function() {
    let project = new Project;
    project._id = 'iwhxu27i';
    project.name = 'foo bar';
    project.email = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7a1a8a887a5e9a6b5">[email protected]</a>';
    return project;
  }


  beforeEach(() => {
    const injector = TestBed.configureTestingModule({
      providers: [ProjectService]
    });

    service = injector.get(ProjectService);
    project = createFakeProject();

  });

  it('should be able to CREATE a new project (async)',
    async( (done) => {
    service.saveProject(project).then( 
      response => {
        expect(response).toEqual(project);
        done();
      } );

  }));

});

I have been struggling with this issue for quite some time now. Perhaps I need to utilize fakeAsync and tick()? Though, using fakeAsync doesn't feel like the ideal solution. It appears that calling done() within a .finally() block might be necessary, however, .finally() seems to not be a method. As I am relatively new to testing Promises with Jasmine, it's possible that I am overlooking something obvious. If you know of any code snippets (or example codes) incorporating Angular 2, Jasmine, and promises, I would greatly appreciate your assistance.

I prefer not to mock PouchDB and concoct my custom stubbed Promise.

Despite the fact that this test should technically fail since the response != project, it passes without any issues. However, the error message persists in my console. Any guidance or advice would be highly valuable. Thank you!

Answer №1

Make sure to handle the promise returned by

service.saveProject(project).then(
. You can either remove the async from the method and return this promise from the test, or await the promise result in the test.

it('is possible to ADD a new project (asynchronous)',
    async (done) => {
      let response = await service.saveProject(project)
      expect(response).toEqual(project);
  });

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

Challenge with Angular dependencies: Transitioning from Windows to Linux

I'm facing a challenge with hosting an Angular application on Linux for a client. The application runs smoothly on Windows where the customer develops it. My NodeJS version is 19. Upon running npm install, I encountered this error message: npm notice ...

What is the process for transferring a Pulumi Output<T> to the container definition of a task in ECS?

When creating a generic ECS service that deals with dynamic data, it is important to note that the containerDefinition within a Task Definition must be provided as a single valid JSON document. The code snippet for this setup looks like: genericClientServi ...

Downloading fonts from Google Fonts is always a struggle when using Next.js

After initializing a fresh Next.js project using create-next-app, I managed to successfully launch it with npm run dev. However, an issue arises every time Next.js boots up, displaying the following error: FetchError: request to https://fonts.gstatic.com/ ...

"Creating a visual representation of models exchanged between the client and server through Rest

Currently, I am working on a project that involves client-server communication via rest API, with Angular 2 calling restful web services as the primary method. The client side is written in Typescript, which is a subset of JavaScript. My main challenge li ...

Executing invisible reCAPTCHA2 in Angular 6: A step-by-step guide

Recently, I have been trying to implement an invisible captcha into my website. In order to achieve this, I turned to the guidance provided by Enngage on their ngx-captcha GitHub page: https://github.com/Enngage/ngx-captcha While following the instruction ...

Postpone the NgModule declaration by importing the module asynchronously

I am facing a challenge in dynamically importing a third-party module and then checking if it exists. The decision to declare it in the NgModule depends on its existence (true/false). Below is an example of my code. However, the issue arises because the ...

Guide on using automapper in typescript to map a complex object to a "Map" or "Record" interface

I have been utilizing the automapper-ts with typescript plugin for automatic mapping. Check it out here While it works smoothly for simple objects, I encountered issues when dealing with complex ones like: Record<string, any> or Map<string, Anoth ...

Attempting to integrate a new feature into the smart admin platform

I've been tasked with enhancing an existing website that was originally created using the Smart Admin template. My first step is to add a new component to the dashboard. Here are the specific commands and steps I followed: -Using the command line: ...

The e2e Protractor test is unable to identify the Angular component within a complex Angular router with multiple layers

I am currently working on an Angular application and I need to set up end-to-end testing for this project. Angular Package: 4.6.6 Protractor: 5.3.0 In addition, my project includes a multi-layer router that wraps the router-outlet into another component ...

Extend the express request object with Typescript and then export the modified object

Seeking to enhance the Request object from express with custom fields using typescript. Based on this particular source, I created a file named @types/express/index.d.ts containing the following code : import { MyClass } from "../../src/MyClass" ...

Using vue-class-component: A guide on creating and setting up reactive data

I am currently working with Vue.js using TypeScript and vue-class-component. My goal is to create a custom component with reactive data. Below is the code I have so far: <template> <div> <input v-model="data.name" placeholder=" ...

Utilizing a file type validator in SurveyJs: A guide

Is there a way to validate uploaded documents on a form using surveyJs and typescript with a custom validator before the file is uploaded? The current issue I am facing is that the validator gets called after the upload, resulting in an API error for unsup ...

Utilize the multipart/form-data approach for sending files with Angular 6

I attempted to send two fields to a backend service. One field is a typical string, while the other is a file field. However, when I utilize the post method of the Http Client, I encounter a 500 Error from the server notifying me that the content-type is n ...

Implement handleTextChange into React Native Elements custom search bar component

I need help with passing the handleTextChange function in the SearchBarCustom component. When I try to remove onChangeText={setValue} and add onchange={handleTextChange}, I am unable to type anything in the search bar. How can I successfully pass in the ...

It appears that the ngOnInit function is being activated prior to receiving any data through the Input()

For a personal challenge, I am working on creating a website that showcases a list of League Of Legends champions. Users can click on the champion icons to access more details. However, I am facing an issue where the champion details (specifically images) ...

Troubleshooting Typescript app compilation problem in a Docker environment

I am encountering a challenge while trying to build my typescript Express app using Docker. Surprisingly, the build works perfectly fine outside of Docker! Below is the content of my Dockerfile: FROM node:14-slim WORKDIR /app COPY package.json ./ COPY yarn ...

Exploring various instances of an Angular 2 component to showcase diverse data

In one of my Angular 2 applications, I have a basic side menu that displays a list of different classRoom options, each with its own set of users. To switch between the various class rooms, I use the routerLink feature provided by Angular. The issue I am ...

How to assign attributes to all child elements in Angular?

I have a unique component in Angular that I utilize throughout my app. It's a button component which I use by calling <app-delete-btn></app-delete-btn> wherever needed. I tried to set the tabindex="1" attribute for my component ...

There was an issue with the program: "ERROR TypeError: When trying to call a method from the

Hey everyone, I'm attempting to retrieve data from an API using a specific service and then log the data in the console. However, I'm encountering an error with the component and service I'm using that reads: ERROR TypeError: Cannot read pro ...

Is there a way to specifically target the MUI paper component within the select style without relying on the SX props?

I have been experimenting with styling the Select MUI component using the styled function. I am looking to create a reusable style and move away from using sx. Despite trying various methods, I am struggling to identify the correct class in order to direct ...