Skip to content

Instantly share code, notes, and snippets.

@rakibulhaq
Last active October 16, 2019 11:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rakibulhaq/dae580f11570c3ea9a35dcd8cf29ab9b to your computer and use it in GitHub Desktop.
Save rakibulhaq/dae580f11570c3ea9a35dcd8cf29ab9b to your computer and use it in GitHub Desktop.
process.env.NODE_ENV = "test";
const app = require("../app");
const chai = require("chai");
const request = require("supertest");
const expect = chai.expect;
const mongoose = require("mongoose");
process.env.TEST_SUITE = "testdb";
beforeEach(async () => {
if (mongoose.connection.readyState === 0) {
const options = {
useNewUrlParser: true,
autoIndex: false, // Don't build indexes
reconnectTries: 30, // Retry up to 30 times
reconnectInterval: 500, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
// If not connected, return errors immediately rather than waiting for reconnect
bufferMaxEntries: 0
};
const dbConnection = mongoose.connect(
`mongodb://localhost:27017/${process.env.TEST_SUITE}`,
options,
function(err) {
if (err) {
throw err;
}
clearDB();
}
);
} else {
clearDB();
}
});
function clearDB() {
for (var i in mongoose.connection.collections) {
mongoose.connection.collections[i].deleteMany();
}
}
describe("User Endpoint", () => {
describe("GET /users", () => {
it("login required", async () => {
const userList = await request(app).get("/users");
expect(userList.status).to.eql(401);
});
});
describe("GET /users", () => {
it("should give user list against proper authentication", async () => {
const newUser = await request(app)
.post("/users")
.send({ userName: "testUser", password: "test123456" });
const authenticatedUser = await request(app)
.post("/auth")
.send({ userName: "testUser", password: "test123456" });
let token = authenticatedUser.body.data.token;
const userList = await request(app)
.get("/users")
.set("Authorization", `Bearer ${token}`);
expect(userList.body.success).to.be.true;
});
});
describe("POST /users", () => {
it("should create a new user", async () => {
const resp = await request(app)
.post("/users")
.send({
userName: "testUser",
name: "Mr. Test User",
password: "test123456",
age: "27",
email: "test@mail.com",
sex: "M",
type: "admin",
status: "active"
});
expect(resp.status).to.eql(200);
expect(resp.body.success).to.be.true;
expect(resp.body.data).to.have.property("_id");
expect(resp.body.data.userName).to.eql("testUser");
});
});
});
afterEach(() => {});
after(async () => {
mongoose.disconnect();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment