Created
September 16, 2018 12:50
-
-
Save Fabianopb/efa48f1da1097fb863c5e87f41d44be3 to your computer and use it in GitHub Desktop.
Testing backend for express-react-ts-ci Medium post
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import MongodbMemoryServer from "mongodb-memory-server"; | |
import * as mongoose from "mongoose"; | |
import * as request from "supertest"; | |
import app from "../app"; | |
import User from "../users/user.model"; | |
import Item from "./item.model"; | |
describe("/api/items tests", () => { | |
const mongod = new MongodbMemoryServer(); | |
let token: string = ""; | |
// Connect to mongoose mock, create a test user and get the access token | |
beforeAll(async () => { | |
const uri = await mongod.getConnectionString(); | |
await mongoose.connect(uri, { useNewUrlParser: true }); | |
const user = new User(); | |
user.email = "[email protected]"; | |
user.setPassword("test-password"); | |
await user.save(); | |
const response = await request(app) | |
.post("/api/users/login") | |
.send({ email: "[email protected]", password: "test-password" }); | |
token = response.body.token; | |
}); | |
// Remove test user, disconnect and stop database | |
afterAll(async () => { | |
await User.remove({}); | |
await mongoose.disconnect(); | |
await mongod.stop(); | |
}); | |
// Create a sample item | |
beforeEach(async () => { | |
const item = new Item(); | |
item.name = "item name"; | |
item.value = 1000; | |
await item.save(); | |
}); | |
// Remove sample items | |
afterEach(async () => { | |
await Item.remove({}); | |
}); | |
it("should get items", async () => { | |
const response = await request(app) | |
.get("/api/items") | |
.set("Authorization", `Bearer ${token}`); | |
expect(response.status).toBe(200); | |
expect(response.body).toEqual([expect.objectContaining({ name: "item name", value: 1000 })]); | |
}); | |
it("should post items", async () => { | |
const response = await request(app) | |
.post("/api/items") | |
.set("Authorization", `Bearer ${token}`) | |
.send({ name: "new item", value: 2000 }); | |
expect(response.status).toBe(200); | |
expect(response.body).toBe("Item saved!"); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment