Testing loopback routes with supertest, mocha, and data models

In a recent discussion on the deprecation of loopback-testing posted on Google groups, there was a query about demonstrating testing without using loopback-testing. The solution proposed in the conversation suggested utilizing supertest instead.

After experimenting with Mocha, supertest, and models sourced from app.js, I encountered an issue. While running a test file independently yielded successful results, integrating it with another test file caused unexpected failures in the first test file. This behavior left me puzzled.

Could my approach to using models be incorrect based on the example below?

describe('/Student', function () {

    var server = require('../server/server')
    var loopback = require('loopback')
    var supertest = require('supertest')
    var request = require('supertest')(server)

    var dataSource = server.dataSource('db', {adapter: 'memory'})

    var Student = dataSource.define('Student', {
        'id': Number,
        'points': Number
    });

    beforeEach(function () {
        Student.updateOrCreate({id: 1, points: 5000});
    })


    it('Post a new student', function (done) {
        request.post('/api/Students').send({points: 5000}).expect(200, done)

    })


})

Answer №1

After receiving feedback from jakerella on the previous answer, I made changes to the code above to avoid having to redefine models from scratch in the code (thank you jakerella!)

With the following code, I am able to execute all tests from various models as a single suite using npm test with no failures.

Given my focus is only on individual orders... listening and closing were unnecessary. It appears that testing overall instances of created models would necessitate their use.

describe('/Student', function () {

    var server = require('../server/server')
    var request = require('supertest')(server)
    var expect = require('expect.js')

    var Student 

    before(function() {
        Student = server.models.Student    
    })

    beforeEach(function (done) {
        Student.upsert({id: 1, points: 5000}, function() { done() })
    })    

    it('Post a new student', function (done) {
        request.post('/api/Students').send({points: 5000}).expect(200, done)
     })
})

Answer №2

Let's address an issue in your code snippet. Initially, there was a problem with the undefined dataSource variable. Additionally, you redefined the Student in your test cases. My suggestion is to utilize the LoopBack application and models that are already defined (usually located in common/models/). For testing purposes, consider implementing a basic structure similar to the code snippet below (using mocha and chai). Pay attention to the use of beforeEach and afterEach functions to initiate and terminate the server operation.

var assert = require('chai').assert,
    superagent = require('superagent'),
    app = require('../server/server');

describe('Person model', function() {
  var server;

  beforeEach(function(done) {
    server = app.listen(done);
  });

  afterEach(function(done) {
    server.close(done);
  });

  it('should successfully login and logout from the live server', function(done) {
    superagent
      .post('http://localhost:3000/api/People/login')
      .send({ email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c464344426c484349024f4341">[email protected]</a>', password: 'foobar' })
      .set('Accept', 'application/json')
      .set('Content-Type', 'application/json')
      .end(function(err, loginRes) {
        if (err) { return done(err); }

          assert.equal(loginRes.status, 200);
          assert.ok(loginRes.body);
          assert.equal(loginRes.body.userId, 1);
        }
      });
  });
});

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

Tips for adding multiple entries to a TransactionWould you like to know

I have a question regarding SQL Server transactions I need to insert data into both Table_A and Table_B. Table_B includes a key from Table_A, and the number of records in Table_B with the Table_A key can vary. [Table_A] id: , title: [Table_B] ...

Issues with calculating SUM in MySQL within a Node.js Express application using EJS template

I am currently working on developing a dashboard for my Node.js project. The aim is to calculate the sum of certain values for an overview. While the SELECT statement works fine in my MySQL database, when I incorporate it into my Node project, I do not rec ...

Tips for extracting dynamically loaded content from a website using Node.js and Selenium?

I'm currently encountering some challenges when trying to scrape a website that utilizes react for certain parts of its content, and I'm unsure about the reason behind my inability to extract the data. Below is the HTML structure of the website: ...

Express tutorial: Implementing view engine for routing

I have encountered an issue while attempting to utilize the ejs view engine in order to access a file without the .html extension at the end of the URL. However, I am receiving an error. const express = require('express') const app = express() c ...

Installing and running Node.js within a tomcat server

After creating a web application using Angular, Node/Express, and MySQL, I faced an issue with deployment. My Angular app is running on a tomcat server connected to multiple PCs, but now I need to also deploy my backend (Node.js/Express.js) on the same s ...

dealing with the same express routes

I'm currently in the process of developing an application using NodeJS/Express/Mongoose. One of the challenges I'm facing is defining routes for suspending a user without causing any duplication. At the moment, I have routes set up for creating ...

What is the method to display a value in an input field using ExpressJS?

Currently, I am delving into ExpressJS and have bootstrapped an application. While working on a basic login feature, I encountered a scenario where the user would enter the correct email but an incorrect password. In such cases, an error message for ' ...

What is the method to extract a specific portion of a file in Node.js?

Is there a way to read a buffer in a file while streaming, by specifying both a start and end position? ...

Postgres Rows Reflecting Added Property Always Display as Undefined

After retrieving objects from my postgres database, I am attempting to add a new property to each object. Strangely, when I log the entire object, the new property appears as expected. However, whenever I try to access or store this new property in another ...

The Express generator automatically generates Pug files in the view folder

While developing a web application using node.js, express, and the express generator, I noticed that the template files in the "view" folder end with .pug extensions. Shouldn't they be .ajs files instead? Is there a way to change this setting? I&apos ...

NPM Error: Module 'balanced-match' Not Found

After updating the node and npm using nvm, I encountered an error when starting the node server. Despite trying various solutions suggested in stack overflow, none seemed to work for me. Below are the steps I tried: 1. Removed node modules and installed t ...

The contents of req.body resemble an empty {}

Does anyone know why the req.body is empty in this code snippet? Even though all form data is submitted, it doesn't seem to be recognized in the req.body. Strangely enough, it works perfectly fine in postman. Take a look at the server-side code: con ...

Errors encountered when using npm in conjunction with Java

Looking to install a Java based package using NPM, but the usual npm install java isn't working for me. Encountering an error when trying to install the package: ld: warning: directory not found for option '-L/Library/Java/JavaVirtualMachin ...

Digital Asset Ledger Project now has Node.js integrations available

I am currently engaged in the Digital Asset Getting Started journey with Node.js bindings. When I execute npm install @da/daml-ledger This triggers the error message below: npm ERR! code E401 npm ERR! 401 Unauthorized: @da/daml-ledger@latest npm ERR! ...

What is the best way to manage errors on my server to ensure it remains stable and never crashes?

Consider this server route example using expressjs: app.get('/cards', function(req, res) { anUndefinedVariable // Server doesn't crash dbClient.query('select * from cards', function(err, result) { anUndefinedVariab ...

What are the steps to install an outdated version of Node.js on a Windows computer?

I recently downloaded a package from https://nodejs.org/dist/. Upon attempting to run the Application file Node.exe, I found that it simply opens a terminal and does nothing. After downloading, I struggled to figure out the installation process. The reas ...

Troubleshooting: How to resolve the issue of "Error [ERR_HTTP_HEADERS_SENT]: Unable to set headers after they have been sent to the client"

* **> const PORT=8000 const express = require('express') const {v4:uuidv4}=require('uuid') const bcrypt =require('bcrypt') const jwt =require('jsonwebtoken') const cors=require('cors') const {MongoClie ...

Serve the JS files in Express separately

I am facing issues with my webapp loading too slowly when using the express.static middleware to serve all my js files. I am considering serving each js file only when needed, such as when serving the html from jade that uses the js file. I have attempted ...

Is it necessary to use next() in express routes?

Many instances in Nodejs/Express showcase that calling next() is not always necessary for success. exports.postLogin = (req, res, next) => { passport.authenticate("local", (err, user, info) => { if (err) { return next(err); } re ...

Making fun of an ES6 class function

Currently, I am in the process of testing an express app, which includes the following files: app.js const express = require('express'); const path = require('path'); const apiRouter = require('./api'); const app = expre ...