Initiate and terminate server using supertest

I've developed a server class that looks like this:

import express, { Request, Response } from 'express';

export default class Server {
  server: any;

  exp: any;

  constructor() {
    this.exp = express();
    this.exp.get('/', (_req: Request, res: Response) => {
      res.json('works');
    });
  }

  start(): void {
    this.server = this.exp.listen(3000);
  }

  stop(): void {
    this.server.close();
  }
}

For end-to-end testing, I'm utilizing supertest. My goal is to initiate my application beforeAll tests and terminate it once the tests are completed.

While it's straightforward to achieve this using beforeAll and afterAll by instantiating the Server class and invoking the start and close methods, I have numerous controllers to test, making it inconvenient to start and stop the server for each test file.

After exploring the documentation, I came across the setupFiles and setupFilesAfterEnv, but I struggled with stopping the server since the instance isn't shared between the two files.

Here's an example of a test file:

import supertest from 'supertest';

describe('Album Test', () => {
   let app: App;

   beforeAll(async (done) => {
     app = new App();

     await app.setUp(); // establishing database connection
     done();
   });

   afterAll(async (done) => {
     await app.close();

     app.server.stop();
     done();
   });

  const api = supertest('http://localhost:3000');

  it('Hello API Request', async () => {
    const result = await api.get('/v1/user');
    expect(result.status).toEqual(200);
    ...
  });
});

Although this approach works well, I find myself duplicating these beforeAll and afterAll methods in every test file. Is there a way to declare them only once?

Thank you

Answer №1

Give this code a try for successful results

const request = require('request')
const app = require('../../app')

describe('test::app', function(){

  let server = null
  let req = null

  before(function(done){
    server = app.listen(done)
    req = request.agent(server)
  })

  after(function(done){
    server.close(done)
  })

  it('should access /api/v1/data/12345 endpoint', function(){
    return req.get('/api/v1/data/12345')
      .expect(200, { result: {} })
  })

})

Answer №2

If you want to globally set up test fixtures, you can utilize the setupFiles feature. This allows you to define variables that can be accessed across multiple test files by assigning them to Node.js' global object.

For example:

app.ts:

import express, { Request, Response } from 'express';

export default class Server {
  server: any;
  exp: any;

  constructor() {
    this.exp = express();
    this.exp.get('/', (_req: Request, res: Response) => {
      res.json('works');
    });
  }

  start(): void {
    this.server = this.exp.listen(3000);
  }

  stop(): void {
    this.server.close();
  }
}

app.setup.js:

const App = require('./app').default;

beforeAll(() => {
  global.app = new App();
  global.app.exp.set('test setup', 1);
  console.log('app setup');
});

afterAll(() => {
  console.log('app stop');
});

jest.config.js:

module.exports = {
  preset: 'ts-jest/presets/js-with-ts',
  testEnvironment: 'node',
  setupFilesAfterEnv: [
    './jest.setup.js',
    '/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/stackoverflow/61659975/app.setup.js',
  ],
  testMatch: ['**/?(*.)+(spec|test).[jt]s?(x)'],
  verbose: true,
};

a.controller.test.js:

describe('controller a', () => {
  it('should pass', () => {
    console.log('test setup:', global.app.exp.get('test setup'));
    expect(1 + 1).toBe(2);
  });
});

b.controller.test.js:

describe('controller b', () => {
  it('should pass', () => {
    console.log('test setup:', global.app.exp.get('test setup'));
    expect(1 + 1).toBe(2);
  });
});

Here are the unit test results:

 PASS  stackoverflow/61659975/a.controller.test.js
  controller a
    ✓ should pass (5ms)

  console log
    app setup

      at Object.<anonymous> (stackoverflow/61659975/app.setup.js:6:11)

  console log
    app setup

      at Object.<anonymous> (stackoverflow/61659975/app.setup.js:6:11)

  console log
    test setup: 1

      at Object.<anonymous> (stackoverflow/61659975/b.controller.test.js:3:13)

  console log
    test setup: 1

      at Object.<anonymous> (stackoverflow/61659975/a.controller.test.js:3:13)

  console log
    app stop

      at Object.<anonymous> (stackoverflow/61659975/app.setup.js:10:11)

  console log
    app stop

      at Object.<anonymous> (stackoverflow/61659975/app.setup.js:10:11)

 PASS  stackoverflow/61659975/b.controller.test.js
  controller b
    ✓ should pass (3ms)

Test Suites: 2 passed, 2 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        6.749s, estimated 12s

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

angular interpolation:issue arises when inserting URL stored in a variable

A challenge I'm facing involves adding a dynamic id to a YouTube URL, which looks something like this: <iframe width="460px" height="415px" ng-src="{{post.youtube_id}}" frameborder="0" allowfullscreen></iframe> One of the URLs I'm a ...

How can I design customized user profile pages with parameters in expressjs, such as creating a URL like website.com/@username?

I am currently facing an issue where my code is not rendering other pages like website.com/settings anymore, while this particular section works fine: router.get('/:@username',(req, res)) => { res.render('profile&apos ...

Searching for an object in Vue 3 Composition API and displaying its contents

Experiencing a challenge with my first Vue.js project, seeking assistance in resolving the issue. Upon receiving a response from my API, I retrieve a list of projects and aim to locate the one matching the ID provided in the URL parameter. A peculiar error ...

multiples of order quantities in WooCommerce

In order to implement a minimum order quantity based on category, I came across this code. However, it seems to apply to all products in the cart. What additional modifications would be needed to specify certain categories? My objective is for customers t ...

"Utilizing Vue Mixins on a global scale, but restricting their usage to local components

Is there a way to use a mixin in multiple components without having to constantly import and declare it? I've tried connecting the mixin object to a global variable using vue.prototype, but mixins are added to components before globals are accessible. ...

What is the reason for instances being compatible even if their class constructors do not match?

Why are the constructors in the example below not compatible, but their instances are? class Individual { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } } class Worker { name: st ...

A guide to setting up Ghost in a subdirectory within an express application

I have an existing website built using express and I want to integrate a "/blog" section powered by Ghost. After adding Ghost to my dependencies, installing it, and setting the urls in Ghost's config file to localhost:3000/blog, I am encountering some ...

Capture data from Ajax requests and store them in PHP variables

When setting up a DDBB Insert using $.ajax, I encountered an issue. $(document).on('click','.submitMessage', function(){ content=$('textarea').val(); img=$('#messageImg').val(); stdMsg=$('.ms_stdMsg ...

Error in IONIC 3: The code is unable to read the 'nativeElement' property due to an undefined value, resulting in a TypeError

I am currently learning about IONIC 3 and working on an app that utilizes the Google Maps API. However, when I try to launch my app, I encounter the following error message: inicio.html Error: Uncaught (in promise): TypeError: Cannot read property ' ...

A guide on retrieving TypeScript mongoose/typegoose schema

Here is a defined schema for an account class AccountSchema; Below is the model declaration for the account const AccountClass: Model<AccountSchema & Document>; class Account extends AccountClass; Why isn't this functioning as expected? ...

Implementing NgRx state management to track and synchronize array updates

If you have multiple objects to add in ngrx state, how can you ensure they are all captured and kept in sync? For example, what if one user is associated with more than one task? Currently, when all tasks are returned, the store is updated twice. However, ...

React app's compilation is failing due to non-compliant ES5 code generation of the abab module, resulting in errors on IE

Can anyone explain why a create-react-app project using TypeScript and configured to generate ES5 code is not functioning on IE11 due to the "atob" function from the 'abab' package not being compiled into ES5 compliant code? module.exports = { ...

Adding more dynamic parameters to the external script in index.html using Vue.js

I am looking to pass username and userEmail from the getters/user method in Vuejs, which is within index.html. Here is an example of how I would like it to be passed: <script>window.appSettings={app_id:"appId", contact_name: "Alexander ...

What is the best way to implement a conditional check before a directive is executed in Angular, aside from using ng-if

I am facing an issue where the directive is being executed before the ng-if directive. Is there a way to ensure that the ng-if directive is executed before the custom directive? Could I be making a mistake somewhere? Should I consider using a different ...

What are the benefits of using Lifery Ajax URLs?

I'm currently using the Grails portlets plugin and I'm exploring how to properly route AJAX methods. It seems like <portlet:actionURL> is only able to map to methods that return models for GSPs, while <portlet:resourceURL> doesn&apos ...

How come my date computed property does not update reactively when changes occur?

I have a Date object in my data, and I need to convert the date into a string for a date picker component in Vuetify. The initial date is being read and displayed correctly. I am able to set the date as well - when I set a code breakpoint, I can see the ...

What steps should I take to fix the issue of "[ERR_REQUIRE_ESM]: Must use import to load ES Module" while working with D3.js version 7.0.0 and Next.js version 11.0.1?

Encountered a roadblock while integrating D3 with Next.js - facing an error when using D3.js v7.0.0 with Next.js v11.0.1: [ERR_REQUIRE_ESM]: Must use import to load ES Module Tried utilizing next-transpile-modules without success Managed to make D3.js ...

Pressing a key once causing two actions when managing content in a separate window

Issue: I am facing a problem where I receive double keypresses from one key event when the event updates content in two separate windows. (Please keep in mind that I am not an expert in this field and appreciate your understanding.) I am attempting to use ...

Simple authentication with ExpressJS, integrated with MongoDB and AJAX technology

I'm developing a simple Express login feature where a user can enter an existing username from MongoDB into a prompt: HTML code that is not directly related to the issue: <a href="#home" class="login"><span class="fontawesome-circle">< ...

How can I create a script for a sliding/toggling menu?

Not sure if it's appropriate to ask, but I'm currently in search of a slide/toggle menu. Despite my efforts on Google, I haven't been able to find exactly what I need. As someone who is more skilled in HTML/CSS than jQuery or other scripting ...