5

I'm trying to set up a test environment to test my typescript express nodejs endpoints but I can't seem to get it to work. I've installed:

  1. jest
  2. ts-jest
  3. jest-junit
  4. supertest
  5. @types/supertest
  6. @types/jest

this is how spec file looks:

import * as request from 'supertest';
import seed from '../../modules/contract/seed'; //empty seed function
import app from '../../index'; // export default app which is an express()

beforeAll(seed);

describe('contractService', () => {
  it('getContracts ', async () => {
    const res = await request(app).get('/getContracts');
    console.log(res.body);
  });
  it('makeContract makes and returns a new contract', async () => {
    const res = await request(app)
      .post('/makeContract')
      .send({
        name: 'testContract',
        startDate: '2019-10-3',
        challenges: []
      });
    expect(res.statusCode).toEqual(200);
    expect(res.body.challenges).toEqual([]);
    expect(res.body.name).toEqual('testContract');
    expect(res.body.startDate).toContain('2019-10-3');
  });
});

I get an error at the request(app) saying

This expression is not callable. Type 'typeof supertest' has no call signatures

contractService.spec.ts(1, 1): Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead.

I don't know what to do because if I use require instead of import, I get the next error

TypeError: Cannot read property 'address' of undefined

it('getContracts ', async () => {
     const res = await request(app)
       .get('/')
        ^
       .expect(200);
});

index.ts

import './config/environment';
import http, { Server } from 'http';
import express, { Express, Router } from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import connect from './database/index';
import patientRouter from './services/patientService';
import challengeRouter from './services/challengeService';
import contractRouter from './services/contractService';

let app: Express;

const startServer = async () => {
  try {
    await connect();
    app = express();
    const routes = Router();
    app.use(bodyParser.json());
    app.use(routes);
    // app.get('/', (req: Request, res: Response) => res.sendStatus(200));
    routes.get('/', (req, res) => res.send('OK'));
    // use routers from services
    routes.use('/', patientRouter);
    routes.use('/', challengeRouter);
    routes.use('/', contractRouter);
    const httpServer: Server = http.createServer(app);
    httpServer.listen(process.env.PORT, async () => {
      console.log(`🚀 Server ready at http://localhost:${process.env.PORT}`);
    });
    const shutdown = async () => {
      await new Promise(resolve => httpServer.close(() => resolve()));
      await mongoose.disconnect();
      if (process.env.NODE_ENV === 'test') return;
      process.exit(0);
    };
    process.on('SIGTERM', shutdown);
    process.on('SIGINT', shutdown);
    process.on('SIGQUIT', shutdown);
  } catch (e) {
    console.log(e);
  }
};

startServer();

export default app;

Jest config:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  testMatch: ['<rootDir>/**/__tests__/**/*.spec.ts'],
  testPathIgnorePatterns: ['/node_modules/'],
  coverageDirectory: './test-reports',
  coveragePathIgnorePatterns: ['node_modules', 'src/database', 'src/test', 'src/types'],
  reporters: ['default', 'jest-junit'],
  globals: { 'ts-jest': { diagnostics: false } }
};
4
  • Can you show jest.config.js Commented Oct 18, 2019 at 12:52
  • @winwiz1 I just did Commented Oct 18, 2019 at 19:58
  • I'd suggest to try a setup that is known to work. Like this or that. The second one uses jest and supertest to test express code written in typescript. Commented Oct 19, 2019 at 0:13
  • I'll check them out but I might switch to stubbing requests Commented Oct 19, 2019 at 13:21

1 Answer 1

3

Late to the game, but:

import request from 'supertest';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.