Running tests on functions that are asynchronous is ineffective

Recently, I made the switch from Java to TypeScript and encountered a challenging problem that has been occupying my time for hours.

Here is the schema that I am working with:

const userSchema = new Schema({
username : { type: String, required: true },
passwordHash : { type: String, required: true },
passwordSalt : { type: String, required: true },
email : { type: String, required: true },
emailVerified : { type: Boolean, default: false },
firstName : { type: String, required: true },
lastName : { type: String, required: true },
postUpvotes : [Schema.Types.ObjectId],
postDownvotes : [Schema.Types.ObjectId],
commentUpvotes : [Schema.Types.ObjectId],
commentDownvotes : [Schema.Types.ObjectId],
creationDate : { type: Date, default: Date.now }, };

My current focus is on testing the required fields in my MongoDB database during tests. In order to do this effectively, I have set up specific test cases.

describe('Test required user fields', function(){
    const gandalfTheWizard = new Student();

    it('Test required username',  function() {
        gandalfTheWizard.username = 'cooolboy';

        return gandalfTheWizard.save().then(() => Promise.reject(new Error('Expected method to reject.')),
            err => { return expect(err).to.be.instanceOf(Error) }
        );
    });

    // More test cases for other required fields

    it('Test required lastName - inserts correct object', function() {
        gandalfTheWizard.lastName = 'tes5';

        this.timeout(50000);

        return gandalfTheWizard.save();
    });
});

In addition to these specific test cases, I also have tests where I simply save an object, which passes successfully:

it('Save Student in database', function () {
    Student.findOne({ firstName: 'Harry' }).then(result => {
        if (result != null) {
            expect(result).to.be.null;
        }
    });

    timeWizardHarry.save();

    Student.findOne().then(result => {
        if (result != null) {
            expect(result._id).to.exist;
            expect(result.username).to.equal(timeWizardHarry.username);
            expect(result.email).to.equal(timeWizardHarry.email);
        }
    });
});

I am currently stuck and hoping someone can provide some insight or assistance on this issue. Any help is greatly appreciated. Thank you.

Answer №1

The problem I encountered was my failure to establish a connection with the database. My testing process was flawed and there were issues with setting up the database as well. I overlooked using AWAIT in my code.

import * as mongoose from 'mongoose' 

This line of code was ineffective:

import mongoose from 'mongoose' 

However, replacing it with the above line fixed 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

Creating a gradient background with the makeStyles function

Why is it that the background: 'linear-gradient(to right, blue.200, blue.700)' doesn't work within makeStyles? I just want to add a gradient background to the entire area. Do you think <Container className={classes.root}> should be rep ...

Exciting Angular feature: Dynamic Titles

I am working with an <i> tag <i class="actionicon icon-star" [ngClass]="{'yellow' : data.isLiked}" (click)="Like(data)" aria-hidden="true" title="Liked"></i> In my current set ...

"Error encountered: 'Callable function cannot be invoked on Mongoose model

In my Nest JS service, the code structure is as follows: import { Injectable } from '@nestjs/common'; import { Model } from 'mongoose'; import { InjectModel } from '@nestjs/mongoose'; import { Collection } from './inter ...

Reactive form allows you to easily format dates

Currently, the date displayed is 1/4/2022. We need it to display in the format 01/04/2022. Can we achieve this formatting using reactive forms with the sample Model form provided below? Thank you. How can we format it when starting from transactionStartD ...

Triggering JSON schema validation event in React's Monaco Editor

I am interested in implementing custom JSON schema validation in my Monaco editor setup. Here is the current configuration: <MonacoEditor language="json" value={jsonValue} editorWillMount={(monaco) => { monaco.languages.json.jsonD ...

A keyboard is pressing on tabs and navigating through the app's contents in Ionic 3 on an Android device

I'm currently working on an IONIC 3 app and facing a challenge. When I tap on the ion search and the Keyboard pops up in ANDROID, it disrupts the layout by pushing all the content around. Original screen: https://i.sstatic.net/34iBz.jpg Keyboard m ...

There seems to be an issue with a potentially null object in an Angular project while trying to view a PDF file

IDENTIFY THE ERROR: printContents = document.getElementById('print').innerHTML.toString(); ON LINE 4: print(): void { let printContents!: string; let popupWin!: any; printContents = document.getElementById('print').innerHTM ...

Encountering an issue with Next.js, Typescript, and mongoose when attempting to use `let cached = global.mongoose

I attempted to create a cached mongoose connection for my Next.js + Typescript application, but the code I used was: let cached = global.mongoose; if (!cached) { cached = global.mongoose = { conn: null, promise: null }; } The use of global.mongoose res ...

States are consistently maintained in React and do not impact the rendering process

I am keeping track of a state value by declaring it like this: const [count, setCount] = useState(0); To increment the count: const incrementCount = () => { setCount(count + 1); } I use this function in a loop to iterate through an array, exec ...

Tips for properly utilizing GeolocationPosition in TypeScript

Our goal is to utilize the Geolocation API to access the user's location. This particular code snippet appears to be functioning well: if (navigator.geolocation) { navigator.geolocation.getCurrentPosition((position: GeolocationPosition) => conso ...

The debate between using "this" versus "classname" to access static elements in

When working with TypeScript, I've observed that there are multiple valid approaches for accessing a static class member. class MyClass { private static readonly FOO: string = "foo"; public DoSomething(): void { console.log(MyClass.FOO);} pu ...

Angular Universal causing issues with updating the DOM component

@Component({ selector: 'mh-feature-popup', template: ` <div class="full"> <div> <div class="container-fluid" [@featurepop]="state"> <div class="row"> <div class="col-xs-12 col-md-4 col-md-offse ...

Using Iframe for WooCommerce integration and implementing Facebook login within an Ionic application

I have created an Ionic application that includes an iframe from a Wordpress website. Here is the code snippet from my home.page.ts file: import { Component } from '@angular/core'; import { DomSanitizer } from "@angular/platform-browser"; @Com ...

Is there a more efficient method for coding this switch/case in TypeScript?

I'm working on a basic weather application using Angular and I wanted some advice on selecting the appropriate image based on different weather conditions. Do you have any suggestions on improving this process? enum WeatherCodition { Thunderstorm ...

Correctly inputting the 'in' statement - Avoid using a primitive value on the right side of an 'in' statement

I am currently facing an issue with my React code where I am getting the error message: The right-hand side of an 'in' expression must not be a primitive.. I am unsure about how to resolve this problem effectively: // The goal is to allow nu ...

Is it recommended for TypeScript to automatically resolve the index.ts file as the default module file?

Struggling with getting the module resolution to work in TypeScript. Consider the following file structure: /modulename/index.ts Should it be resolved like this? import * as modulename from "modulename" I can't seem to make it work. However, imp ...

Angular2/TypeScript Coding Guidelines

I am curious about the common practices and consensus among the Angular2 community when it comes to writing reusable code in TypeScript. I have gathered some information and questions related to Angular2 that I would like to discuss. Organizing Module/A ...

What steps do I need to take to enable the about page functionality in the angular seed advance project?

After carefully following the instructions provided on this page https://github.com/NathanWalker/angular-seed-advanced#how-to-start, I successfully installed and ran everything. When running npm start, the index page loads with 'Loading...' I ha ...

How can I display 4 react components, such as custom buttons, in a manner that ensures the most recently pressed button appears on top?

I've been attempting to solve this problem, but I'm struggling to find a solution. My current approach involves grouping the 4 button components in an array and shifting their positions based on user input. Is there a more efficient way to accomp ...

The value stored in Ionic Storage will only be visible on the HTML page after a refresh is performed

After updating my Ionic Storage values, they are not showing up on the HTML page until I reload it. I have researched similar issues faced by others, but the solutions I found either do not work or are no longer applicable due to changes in the Ionic versi ...