0

I would like to test the POST and GET methods of two APIs called Restaurant and Employee. The two APIs work as expected. This question is specifically about how to test the two APIs? I have created 2 test files that I have included below. For orginization purposes, I have put them in 2 separate directories test\restaurant\index.test.ts and test\employee\index.test.ts. When I run the tests individually the test file executes and all tests pass. It seems that when I run the following script npm run knex:latest && npm run test:compile && npm run test:script not all tests work. In particular, that script is supposed to execute all test files. But when I run it not all tests pass. Is there a different way I should setting up these test files so that I can keep the files organized in this way but all tests run without the server not having started?

test\restaurant\index.test.ts

import { before, describe, it, after } from 'node:test';
import assert from 'node:assert';
import { promisify } from 'node:util';
import { Server } from 'http';

describe('Restaurant Test Suite', () => {
  let serverTest: Server;
  before(async () => {
    const { server } = await import('../../src/index');
    serverTest = server;
  });
  after(async () => {
    try {
      await promisify(serverTest.close.bind(serverTest))();
      return process.exit(0);
    } catch (err) {
      console.error(err);
      return process.exit(1);
    }
  });
  it('Restaurant Post', async (t) => {
    const testPort = process.env.PORT;

    const testServerAddress = `http://localhost:${testPort}/api/v1/restaurant`;

    await t.test('it should create a restaurant', async () => {
      const data = {
        name: 'Test Name',
        active: false,
        description: 'Test Description',
      };
      const request = await fetch(testServerAddress, {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      });

      assert.strictEqual(request.status, 200);
      interface Result {
        message: string;
      }
      const result = await (<Promise<Result>>request.json());
      assert.deepStrictEqual(
        result.message,
        'Restaurant created successfully',
        'it should return a valid text message',
      );
    });
  });
  it('Get Restaurants', async (t) => {
    const testPort = process.env.PORT;

    const testServerAddress = `http://localhost:${testPort}/api/v1/restaurants`;

    await t.test('it should get restaurants', async () => {
      const request = await fetch(testServerAddress, {
        method: 'GET',
      });

      assert.strictEqual(request.status, 200);
      interface Data {
        id: string;
      }
      interface Result {
        data: Array<Data>;
      }
      const result = await (<Promise<Result>>request.json());
      console.log(result);
      assert.ok(result.data[0].id.length > 30, 'Restaurant uuid successfully');
    });
  });
});

test\employee\index.test.ts

import { before, describe, it, after } from 'node:test';
import assert from 'node:assert';
import { promisify } from 'node:util';
import { Server } from 'http';

describe('Employee Test Suite', () => {
  let serverTest: Server;
  before(async () => {
    const { server } = await import('../../src/index');
    serverTest = server;
  });
  after(async () => {
    try {
      await promisify(serverTest.close.bind(serverTest))();
      return process.exit(0);
    } catch (err) {
      console.error(err);
      return process.exit(1);
    }
  });
  it('Employee Post', async (t) => {
    const testPort = process.env.PORT;

    // https://nodejs.org/docs/latest-v18.x/api/test.html#mocking
    const testServerAddress = `http://localhost:${testPort}/api/v1/employee`;

    await t.test('it should create a employee', async () => {
      const data = {
        name: 'Test Employee Name',
        employee_availability: []
      };
      const request = await fetch(testServerAddress, {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      });

      assert.strictEqual(request.status, 200);
      interface Result {
        message: string;
      }
      const result = await (<Promise<Result>>request.json());
      assert.deepStrictEqual(
        result.message,
        'Employee created successfully',
        'it should return a valid text message',
      );
    });
  });
  it('Get Employees', async (t) => {
    const testPort = process.env.PORT;

    const testServerAddress = `http://localhost:${testPort}/api/v1/offerings`;

    await t.test('it should get employees', async () => {
      const request = await fetch(testServerAddress, {
        method: 'GET',
      });

      assert.strictEqual(request.status, 200);
      interface Data {
        id: string;
      }
      interface Result {
        data: Array<Data>;
      }
      const result = await (<Promise<Result>>request.json());
      console.log(result);
      assert.ok(result.data[0].id.length > 30, 'Employee uuid successfully');
    });
  });
});

ERROR LOG:

# (node:128) ExperimentalWarning: The Node.js specifier resolution flag is experimental. It could change or be removed at any time.
# (Use `node --trace-warnings ...` to show where the warning was created)
# Subtest: Offering Test Suite
# Error [ERR_SERVER_NOT_RUNNING]: Server is not running.
#     at new NodeError (node:internal/errors:405:5)
#     at Server.close (node:net:2161:12)
#     at Object.onceWrapper (node:events:631:28)
#     at Server.emit (node:events:517:28)
#     at emitCloseNT (node:net:2221:8)
#     at process.processTicksAndRejections (node:internal/process/task_queues:81:21) {
#   code: 'ERR_SERVER_NOT_RUNNING'
# }
# Subtest: /app/test/employee/index.test.js
not ok 2 - /app/test/employee/index.test.js

Any assistance on how to test these two APIs without the server going down halfway through would be much appreciated! Maybe there's something I've missed that I'm unaware of.

2
  • return process.exit(0); why are you tearing everything down after your test? Commented Dec 19, 2023 at 5:40
  • The thought was to exit everything once the test was completed. Should this be set up differently? Commented Dec 19, 2023 at 13:48

0

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.