Testing asynchronous errors with Sequelize and Postgres

Recently, I've been working on writing unit tests for Sequelize with a Postgres database and using Jest for testing. While trying to get the following code to work:

test('email field only takes valid emails', () => {
  expect.assertions(2);
  let user = Users.build({ email: 'notAProperEmail', password: 'abc123' });
  return user.validate().catch(err => {
    expect(err).toHaveProperty('errors');
    expect(err.errors[0].message).toEqual('Validation isEmail on email failed');
  });
})

I encountered an error "SequelizeDatabaseError: relation "Users" does not exist" which puzzled me. Also, the expect method seems to be missed as I receive the assertion error: "Expected one assertion to be called but received zero assertion calls."

describe('Password is encrypted', () => {
beforeAll(() => {
  Users.create({
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="780c1d0b0c49381f1519111456fb84888">[email protected]</a>',
    password: 'testPassword123'
  })
});

test('password is not plain text', () => {
  expect.assertions(1);
  return Users.findOne({where: { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1c5d4c2c580f1d6dcd0d8dd9fd2dedc">[email protected]</a>' }}).then(response => {
    expect(2).toEqual(2)
    console.log('console log here: ', response);
  });
});

I have a hunch that the issue stems from build not saving to the database in time for Jest to make an assertion. Using promises to handle the asynchronous nature seemed like a viable solution according to the Jest documentation. However, even after implementing promises, it still throws an error suggesting that the promises are being resolved before Sequelize finishes fetching data from the Postgres Database. Any insights on this challenge would be highly appreciated!

Answer №1

It took me a little while, but I finally figured out a solution to a similar issue that brought me here! It seems like the problem may stem from an environment issue. When running your test suite with Jest, it searches for the database related to your test environment rather than your dev environment. In my situation, I am utilizing postgres and knex, and the different environment configurations are stored in the knexFile. I would assume that Sequelize operates in a similar manner! To track down the issue, try running psql myDBinWhateverEnv and check if there is a table named "Users" present.

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

Encountered a problem while attempting to remove node version

When I run the command nvm ls -> v4.3.2 system default -> 4.3.2 (-> v4.3.2) node -> stable (-> v4.3.2) (default) stable -> 4.3 (-> v4.3.2) (default) iojs -> N/A (default) Upon running nodejs --version, it returns v0 ...

What is the best way to establish a connection between two services in a Docker-compose setup so that they are able to communicate with each

I'm new to Docker and facing challenges in connecting two separate services using docker-compose. I need to be able to write to a database and read from it. Additionally, each container should be able to ping the other one. When I run docker exec -ti ...

The command is failing to include functionality with the yarg npm package

I have been attempting to incorporate a command using yargs, however, after executing my code, the command does not seem to be added successfully. Below is the snippet of what I am attempting: const yargs = require('yargs') //create add command ...

Browsing data privacy is crucial, which is why I have decided to operate both servers on the same port to ensure that cookies are

In my project, the front end is built with Next.js and the backend uses Express and Node.js. These projects are currently running on different ports - the frontend on port 3000 and the backend on port 8080. While everything works fine locally and cookies a ...

I'm having an issue with the Next.js Image component not functioning properly on the server

The issue with Next.js Image not working on the server but working fine on localhost has been puzzling me. My assumption was that it could be related to permissions, as I fetch images from a third-party domain. However, when I load images using a regular ...

Transform any type of file, whether it be a document, image, or text file

I am looking for a way to convert any type of document, image, or text file into a PDF that is compatible with all operating systems. Although I attempted the method using node-msoffice-pdf, it only seems to work effectively on Windows OS and not on other ...

Global installation of all dependencies listed in the package.json file

When it comes to installing packages globally, we often use the command npm install -g package1 package2. However, I recently uploaded a second app on a server and need to install all the packages listed in the package.json file. Some of these packages wer ...

Even after shutting down my PeerConnection, the black screen persists. I would appreciate assistance in resolving this issue

Welcome to the Room.js Client Side Code! import React, { useEffect, useRef, useState } from "react"; import io from "socket.io-client"; import Peer from "simple-peer"; import styled from "styled-components"; const C ...

Troubleshooting caching problems when deploying a Node.js app on Heroku

Currently, I am facing a challenge while trying to deploy my app on Heroku. Despite being successful in deploying it several times before, I recently updated mongoose from ">= 3.5.0" to ">= 3.6.0rc0" in my packages.json file. The new version 3.6 requires m ...

Express JS offers advanced routing capabilities with its multi-level routing feature

I'm currently working on a straightforward CMS application using Express. The administrator is able to configure routes in the following format: domain/f1/f2/f3/f4/page1 (which will display the page1 view) domain/n1/n2/page2 (which will display the ...

What is the proper way to manage the refresh token on the client's end within a JWT system?

Curious about what exactly occurs on the client side when the refresh token expires. Is the user directed to a login page and remains logged in, or does the client side log them out automatically? My understanding is that the refresh token is saved in an ...

filtering the properties of mongoose documents

I have created a schema as shown below: var UserSchema = new Schema({ firstName: { type: String, required: true }, lastName: { type: String, required: true }, email: { type: String, required: true }, location: { type: String, required: true }, p ...

What was the reason for node js not functioning properly on identical paths?

When the search route is placed at the top, everything works fine. However, when it is placed at the end, the route that takes ID as a parameter keeps getting called repeatedly in Node. Why does this happen and how can it be resolved? router.get('/se ...

Automaton ScheduleTask Feature

I'm struggling to understand how to make this work. My goal is to set up Hubot to automatically call a function at regular intervals in a specific HipChat channel. Currently, I have it working by requiring the user to type "Hubot totalviewers" in the ...

Error: The Service Fabric node.js guest application running an express.js server is encountering an EADDRIN

Uncertain whether this issue stems from Service Fabric or is related to node.js. The problem I'm facing can be found here. Upon initially deploying the node.js application, it runs smoothly. However, upon redeployment, the application fails to functi ...

It is essential for npm to automatically install peer dependencies in the parent project without overlooking them

I am currently facing an issue with publishing a react application, let's call it project-A, as an npm package. This project has several dependencies like material-ui, dompurify, recharts, and more. In another application, project-B ...

Oversee various interactions for the user

I am currently utilizing NodeJs, ExpressJs, and Angular 6 for my application, but I have encountered an issue. Within my system, there is a user with the attributes: User U: { name; email; password; } Let's assume this user, named U, is ...

The functionality of `npm run` does not meet the expected behavior within a Docker container

Currently, I am in the process of developing a React app using Vite and deploying it via Docker containers. However, when attempting to deploy the container, executing npm run build seems to have no effect; even manually running it inside the container doe ...

What are the potential consequences of nodejs operating on a single thread?

The Node.js official website highlights the platform's capabilities, with a focus on building fast and scalable network applications easily. It utilizes an event-driven, non-blocking I/O model that ensures efficiency and is particularly suited for dat ...

Unable to access Docker Flask App connected to Docker DB in browser

I currently have a Flask App running in one Docker container and a Postgres database in another Docker container. I am attempting to build and run these containers using 'docker-compose up --build'. However, when I attempt to open the 'Runni ...