#Jest test cases with sql

1 messages · Page 1 of 1 (latest)

hidden heart
#

I am new to jest and I am trying to connect my MySQL database inside the jest before all function , I think I have understood jest wrong or idk , I want to test my API's on a fake database I created with same schemas by hitting my localhost server url i am using express and typeorm i can give you this sample code

import request from 'supertest';
import { createConnection, getConnection, Connection } from 'typeorm';
import app from '../src/app'; 

let connection: Connection;

beforeAll(async () => {
  connection = await createConnection(); 
});

afterAll(async () => {
  await connection.close();
});

describe('GET /api/users', () => {
  it('should fetch users from the database', async () => {
    const response = await request(app).get('/api/users');
    expect(response.status).toBe(200);
    expect(response.body).toHaveLength(2);e
  });
});

the problem is its not connecting to my database and is getting timed out
am I doing something wrong here? If you have encountered same problem I could use a solution
(also assume i am passing correct credentials inside the create-Connection method)

neat steeple
#

To be honest, It doesn't make sense to me to a DB connection.
You can either connect to your DB or not.
If you want to expose the statuses for each of your services or APIs, that's usually been done by health-checks.

We usually mock external services as they are not something we can really test, we "have" to trust they are properly implemented which sucks. :/

If you need to mock any API call you can also is MSW:
https://mswjs.io/
You can find mocked services or Web APIs like localstorage on NPM or you can implement your own.

hidden heart
#

I am simulating real api testing by jest and supertest by hitting a server with supertest and then validating 200 success response + my response object rtc

hidden heart
neat steeple