Guest User

Untitled

a guest
Sep 16th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. import MongodbMemoryServer from "mongodb-memory-server";
  2. import * as mongoose from "mongoose";
  3. import * as request from "supertest";
  4. import app from "../app";
  5. import User from "../users/user.model";
  6. import Item from "./item.model";
  7.  
  8. describe("/api/items tests", () => {
  9.  
  10. const mongod = new MongodbMemoryServer();
  11. let token: string = "";
  12.  
  13. // Connect to mongoose mock, create a test user and get the access token
  14. beforeAll(async () => {
  15. const uri = await mongod.getConnectionString();
  16. await mongoose.connect(uri, { useNewUrlParser: true });
  17. const user = new User();
  18. user.email = "test@email.com";
  19. user.setPassword("test-password");
  20. await user.save();
  21. const response = await request(app)
  22. .post("/api/users/login")
  23. .send({ email: "test@email.com", password: "test-password" });
  24. token = response.body.token;
  25. });
  26.  
  27. // Remove test user, disconnect and stop database
  28. afterAll(async () => {
  29. await User.remove({});
  30. await mongoose.disconnect();
  31. await mongod.stop();
  32. });
  33.  
  34. // Create a sample item
  35. beforeEach(async () => {
  36. const item = new Item();
  37. item.name = "item name";
  38. item.value = 1000;
  39. await item.save();
  40. });
  41.  
  42. // Remove sample items
  43. afterEach(async () => {
  44. await Item.remove({});
  45. });
  46.  
  47. it("should get items", async () => {
  48. const response = await request(app)
  49. .get("/api/items")
  50. .set("Authorization", `Bearer ${token}`);
  51. expect(response.status).toBe(200);
  52. expect(response.body).toEqual([expect.objectContaining({ name: "item name", value: 1000 })]);
  53. });
  54.  
  55. it("should post items", async () => {
  56. const response = await request(app)
  57. .post("/api/items")
  58. .set("Authorization", `Bearer ${token}`)
  59. .send({ name: "new item", value: 2000 });
  60. expect(response.status).toBe(200);
  61. expect(response.body).toBe("Item saved!");
  62. });
  63. });
Add Comment
Please, Sign In to add comment