Skip to content

Commit

Permalink
Setup tests with jest, add tests on ride.spec.ts (saveNewRide and del…
Browse files Browse the repository at this point in the history
…eteRide)
  • Loading branch information
aureliedev committed Feb 9, 2024
1 parent 1e5ef8e commit 79fa04c
Show file tree
Hide file tree
Showing 8 changed files with 144 additions and 31 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ In parallel, follow log output with:
docker compose logs -f
```

### Run tests

Run tests in watch mode:

```
docker compose exec back-end npm run test:watch
```

### Setting web-app types after GraphQL

Generate query-specific types for web-app development:
Expand Down
4 changes: 2 additions & 2 deletions back-end/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions back-end/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
"main": "index.js",
"scripts": {
"test": "jest",
"test:watch": "jest --watch",
"test:watch": "jest --watchAll",
"build": "tsc",
"start": "node dist/index.js",
"build:watch": "tsc --watch",
"start:watch": "nodemon dist/index.js",
"dev": "npm run build && (npm run build:watch & npm run start:watch)"
},
"author": "Arnaud Renaud",
"author": "Wild Carbon team",
"license": "ISC",
"devDependencies": {
"@types/bcrypt": "^5.0.2",
Expand Down
21 changes: 21 additions & 0 deletions back-end/src/database.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { DataSource } from "typeorm";
import Ride from "./entities/ride";
import Transportation from "./entities/transportation";

let dataSource: DataSource;

export const getDataSource = async () => {
if (!dataSource) {
dataSource = new DataSource({
type: "postgres",
url:
process.env.NODE_ENV === "test"
? process.env.TEST_DATABASE_URL
: process.env.DATABASE_URL,
entities: [Ride, Transportation],
synchronize: true,
});
await dataSource.initialize();
}
return dataSource;
};
91 changes: 89 additions & 2 deletions back-end/src/entities/ride.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,91 @@
import { getDataSource } from "../database";
import Ride from "./ride";
import Transportation from "./transportation";

// TODO: a retirer (Pour tester les commandes et le fonctionnement)
test("test", () => {
expect(1 + 1).toEqual(2);
// test("test", () => {
// expect(1 + 1).toEqual(2);
// });

async function createTransportation() {
const transportation = await Transportation.createTransportationIfNotExisting(
{
id: 1,
label: "voiture",
carboneEmission: 200,
}
);
return { Transportation: transportation };
}

describe("Ride", () => {
beforeEach(async () => {
const database = await getDataSource();
for (const entity of database.entityMetadatas) {
const repository = database.getRepository(entity.name);
await repository.query(
`TRUNCATE "${entity.tableName}" RESTART IDENTITY CASCADE;`
);
}
});

afterAll(async () => {
const database = await getDataSource();
await database.destroy();
});

// Test createRide
describe("saveNewRide", () => {
it("creates ride and returns it", async () => {
const { Transportation } = await createTransportation();

const rideToCreate = {
label: "Test ride",
distance: 100,
date: new Date(),
//transportationId: 1,
};
const returnedRide = await Ride.createRide({
...rideToCreate,
transportationId: Transportation.id,
});

expect(returnedRide).toMatchObject(rideToCreate);
expect(returnedRide.transportation).toMatchObject(Transportation);

expect(await Ride.getRideById(returnedRide.id)).toEqual(returnedRide);
});
});

// Test deleteRide
describe("deleteRide", () => {
it("deletes a ride with id and returns it", async () => {
const { Transportation } = await createTransportation();

// Create a ride
const rideToCreate = {
label: "Test first ride",
distance: 120,
date: new Date(),
transportationId: Transportation.id,
};
const createdRide = await Ride.createRide(rideToCreate);

// Verifie si le trajet à été créé
const retrieveRide = await Ride.getRideById(createdRide.id);
expect(retrieveRide).toMatchObject({
label: rideToCreate.label,
distance: rideToCreate.distance,
// date: expect.any(Date),
});
expect(retrieveRide.transportation).toMatchObject(Transportation);

const deletedRide = await Ride.deleteRide(createdRide.id);

// Tente de récupérer le trajet supprimé, (s'attendant à une erreur ou a null)
await expect(Ride.getRideById(createdRide.id)).rejects.toThrow();

expect(deletedRide.id).toBe(createdRide.id);
});
});
});
10 changes: 5 additions & 5 deletions back-end/src/entities/ride.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@ import {
Entity,
ManyToOne,
PrimaryGeneratedColumn,
} from 'typeorm';
import { ObjectType, Field, ID, Float } from 'type-graphql';
} from "typeorm";
import { ObjectType, Field, ID, Float } from "type-graphql";

import { CreateOrUpdateRide } from './ride.args';
import Transportation from './transportation';
import { CreateOrUpdateRide } from "./ride.args";
import Transportation from "./transportation";

type RideArgs = CreateOrUpdateRide & {};

@Entity()
@ObjectType()
class Ride extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
@PrimaryGeneratedColumn("uuid")
@Field(() => ID)
id!: string;

Expand Down
29 changes: 10 additions & 19 deletions back-end/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,12 @@
import { DataSource } from 'typeorm';
import 'reflect-metadata';
import { Response } from 'express';
import "reflect-metadata";

import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { buildSchema } from 'type-graphql';
import Transportation from './entities/transportation';
import { TransportationResolver } from './resolvers/TransportationResolver';
import Ride from './entities/ride';
import { RideResolver } from './resolvers/RideResolver';

const dataSource = new DataSource({
type: 'postgres',
url: process.env.DATABASE_URL,
entities: [Transportation, Ride],
synchronize: true,
});
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";
import { buildSchema } from "type-graphql";
import Transportation from "./entities/transportation";
import { TransportationResolver } from "./resolvers/TransportationResolver";
import { RideResolver } from "./resolvers/RideResolver";
import { getDataSource } from "./database";

const PORT = 4000;
const startApolloServer = async () => {
Expand All @@ -29,10 +20,10 @@ const startApolloServer = async () => {
listen: { port: PORT },
});

await dataSource.initialize();
await getDataSource();
await Transportation.initializeTransportations();

console.log(`🚀 Server ready at: ${url}`);
};

startApolloServer();
startApolloServer();
8 changes: 7 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ services:
build: ./back-end
environment:
- DATABASE_URL=postgres://postgres:password@database:5432/postgres
- TEST_DATABASE_URL=postgres://postgres:password@test-database:5432/postgres
depends_on:
- database
ports:
Expand All @@ -16,7 +17,7 @@ services:
target: /app
- action: rebuild
path: back-end/package.json

web-app:
build: ./web-app
ports:
Expand All @@ -36,5 +37,10 @@ services:
environment:
- POSTGRES_PASSWORD=password

test-database:
image: postgres:15
environment:
- POSTGRES_PASSWORD=password

volumes:
database-data:

0 comments on commit 79fa04c

Please sign in to comment.