Having trouble parsing the get request using supertest

When testing get requests to my mLab app using supertest, I noticed an issue with the response. The regular GET request from Postman returns this:

{"_id":"5b169a9951573c50d9682d52","text":"First test note","title":"Test1"}

However, the response received in the test contains extra slashes before each quote:

{\\"_id\\":\\"5b169a9951573c50d9682d52\\",\\"text\\":\\"First test note\\",\\"title\\":\\"Test1\\"}

This is a snippet of my test file:

const server = require("../../app/server");

const request = require("supertest")(server);

describe("routes: index", () => {

  test("should respond as expected", async() => {

    const app = request("http://localhost:8000");

    const response = await app.get("/notes/5b169a9951573c50d9682d52");

    expect(response).toEqual("First test note");

    expect(response).toEqual("Test1");

  });

});

Below is my server configuration:

const express = require('express'); // node module 
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require('./config/db');

const app = express();

const port = process.env.PORT || 8000;

app.use(bodyParser.urlencoded({
  extended: true
}));

MongoClient.connect(db.testUrl, (err, database) => {
  if (err) return console.log(err)
  require('./routes')(app, database);
  app.listen(port, () => {
    console.log('We are live on ' + port);
    console.log(process.env.PORT);
  });
})

module.exports = app;

Answer №1

Although I have not personally used supertest, after reviewing your code and documentation, it is evident that there are several issues.

Firstly, what you are seeing in your test framework output is the string representation of the JSON object, which is accurate.

However, the way you are attempting to handle the response is incorrect. I recommend referring to the documentation:

https://www.npmjs.com/package/supertest

I believe you can resolve this issue by: 1) Defining the expected type 2) Accessing the body attribute of the response

const response = await app.get("/notes/5b169a9951573c50d9682d52").set('Accept', 'application/json');

expect(response.body.text).toEqual("First test note");

I hope this solution proves effective for you.

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

Show users who liked a post from 2 different collections in Meteor

How do I retrieve a list of users who have "liked" this post from a collection and display it in a template? Collections: likes: { "_id": 1234, "userId": "1dsaf8sd2", "postId": "123445" }, { "_id": 1235, "userId": "23f4g4e4", "pos ...

Exploring best practices for transmitting JavaScript objects and arrays via forms to servers (JSON/??)

I would like to understand what would be the most effective approach to achieve this: Based on a user selection, generate a list of "selected items" in the following format: {items {categoryString {tag_id1 {[fr]=>itemFR, [en]=>itemEN} {c ...

What is the reason for encodeURIComponent not encoding single quotes or apostrophes?

Although the escape() function was deprecated and replaced by encodeURIComponent, there is an issue with encodeURIComponent as it doesn't encode the single quote/apostrophe character. This poses a problem when trying to escape apostrophes in someone&a ...

In Vue, it is not accurate to measure overflow

I am working on creating an overflow effect with tagging that fades out at the beginning to provide a subtle hint to users that there is more content. Here is what it currently looks like: https://i.stack.imgur.com/fXGBR.png To achieve this, I added a fa ...

The HTML body content of an iframe

Hey there, I'm trying to get just the body html from an iframe using my code. Currently it returns all the html of the iframe. Does anyone have any ideas on how to modify this? Here's the code snippet: alert( $("#uploaderIframe").contents()[0]. ...

how to properly position an image using javascript

I have two tilesheet images and I have successfully rendered them, but I am struggling to figure out how to place the character in front of the map. https://i.stack.imgur.com/n1a3Q.png I have placed these images in two different JavaScript files. This i ...

Finding the appropriate method to access a template variable reference in a designated row of an Angular Material table (Angular 7)

Currently, I am working on implementing a more intricate version of a behavior inspired by Angular Material's tutorials. In my simplified example, an Angular Material table is populated with data from a string array. The first column contains input fi ...

My ExpressJS routes suddenly fail to function, leaving me unable to receive any responses

Currently, my old routes in express js are functioning properly except for one specific route. However, the new routes that I am creating are not working as expected - each time I make a request using Postman, I receive an error stating "couldn't get ...

Nested views within nested views in UI Router

Exploring the capabilities of angular-ui and specifically experimenting with the ui-router module to create nested views. I'm running into an issue where a partial isn't rendering within another partial: The structure of nesting looks like this: ...

Convert a String to JSON using either JavaScript or jQuery

Currently, I am developing a JavaScript animation script and I am aiming to allow individuals to define behavior declaratively within the HTML. This is the format I envision for my HTML: <div data-animation="top: 600, left: 600, opacity: 1, start: 0.2 ...

Swapping out nodes for images using d3.js

Below is the code snippet I am currently executing http://jsfiddle.net/a7as6/14/ I have implemented the following code to convert a node to an image: node.append("svg:image") .attr("class", "circle") .attr("xlink:href", "https://github.com/favico ...

Why is it that one function does not hold off on execution until Promise.all() is resolved in another function?

I am currently working on a form that allows users to upload files seamlessly. <form @submit.prevent="sendForm" enctype="multipart/form-data"> <input multiple ref="PostFiles" name="PostFiles" type="file" @change="selectFile('add')"> ...

Error: The property 'language' is undefined and cannot be read

Struggling to execute the App-test.js file provided by React Native in the __test__ directory: import 'react-native'; import React from 'react'; import App from '../src/app'; // Note: test renderer must be required after rea ...

String includes another String not refreshing automatically

How come myCtrl.greeting doesn't automatically update when I change myCtrl.name? angular.module('MyApp', []) .controller('MainController', [function(){ var mCtrl = this; mCtrl.name = ''; mCt ...

Axios has encountered a status code 429 and the request has failed

I've been encountering a recurring issue while trying to extract and save a large amount of data from an external API endpoint to my Database. The error code 429 keeps popping up. Despite attempting to use timeout and sleep libraries, I haven't ...

Is it possible to initially design a login page using HTML/CSS and JavaScript, and then integrate VUE into it?

As part of a school project, I am tasked with developing a web-based application for a library system. The goal is to create a platform where librarians can login and manage books by adding, removing, or editing them. My responsibility lies in handling the ...

What are the steps to resolve the issue of encountering the error message "Unrecognized custom element: <bot-ui>"?

I'm having some trouble setting up a chatbot screen with the "botui" and "vue-cli". Whenever I try to display the screen, I encounter an "Unknown custom element: " error. Below is the code snippet that I am using. Can you please help me figure out ...

Extract information from a JavaScript function utilizing Python's Selenium

Is there a way to extract data from within a JavaScript function using Selenium? Visit the page here Here is the input code: <script type="text/javascript"> var chartData1 = []; var chartData2 = []; var chartData3 = []; ... ...

Employing square bracket notation based on the input data

I'm currently in the process of enhancing some code within my library, but I've encountered a perplexing issue with bracket notation not functioning as expected when attempting to call an imported class. The parameter type expects a camelCased s ...

What are some tactics for circumventing the single-page framework behavior of next.js?

How can I change the behavior of next.js to load each URL with a full reload instead of acting like a one-page framework? ...