All files / app/routes/api/group/group-id/delete delete-group.integration.spec.ts

100% Statements 56/56
100% Branches 0/0
100% Functions 16/16
100% Lines 55/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191  1x 1x 1x 1x 1x 1x         1x 1x   1x 1x           1x             1x 6x 6x   6x     6x     6x       6x           6x   6x   6x       1x 6x     1x 1x   1x     1x 1x         1x   1x       1x         1x     1x           1x           1x           1x         1x         1x     1x           1x           1x             1x 1x   1x         1x     1x     1x     1x                   1x 5x           5x             1x           1x     1x 1x      
/* eslint-disable @typescript-eslint/no-explicit-any */
import config from '../../../../../config';
import request from 'supertest';
import app from '../../../../../app';
import db, {syncPromise} from '../../../../../db';
import {expect} from 'chai';
import {
  GroupNotFoundError,
  NotMemberOfGroupError,
  NotOwnerOfGroupError,
} from '../../../../../errors';
import {Group, GroupService, Membership, User} from '../../../../../models';
import sinon from 'sinon';
 
describe('delete /api/group/:groupId', function() {
  const csrfHeaderName = config.jwt.securityOptions.tokenName.toLowerCase();
 
  let csrf: string;
  let user: any;
  let agent: request.SuperTest<request.Test>;
 
  const signUpBody = {
    username: 'test',
    email: 'test@mail.com',
    password: 'password',
  };
 
  // Force sync database before each test
  beforeEach(async function() {
    await syncPromise;
    await db.sync({force: true});
 
    agent = request.agent(app);
 
    // Get csrf token
    csrf = await agent.head('/auth')
        .then((response) => {
        // Save jwt cookie
          return response.header[csrfHeaderName];
        });
 
    // Sign up to access api and set new jwt
    await agent
        .post('/auth/sign-up')
        .set(csrfHeaderName, csrf)
        .send(signUpBody)
        .expect(201)
        .then((response) => {
          user = response.body;
        });
    csrf = await agent.head('/auth')
        .then((response) => {
          return response.header[csrfHeaderName];
        });
  });
 
  afterEach(function() {
    sinon.restore();
  });
 
  it('is only accessible if user is logged in', async function() {
    await agent.put('/auth/logout').set(csrfHeaderName, csrf).expect(204);
 
    await agent.delete('/api/group/3').expect(401);
  });
 
  it('responses with 400 if groupId is not a number', function() {
    return agent.delete('/api/group/test')
        .set(csrfHeaderName, csrf)
        .expect(400);
  });
 
  it('responses with NotMemberOfGroupError if user tries to delete a ' +
      'group he/she is not a member of', function() {
    return agent.delete('/api/group/1')
        .set(csrfHeaderName, csrf)
        .expect(401)
        .then((res) => {
          expect(res.body.message).to
              .be.eql(new NotMemberOfGroupError().message);
        });
  });
 
  it('responses with NotOwnerOfGroupError if user is a member the group ' +
      'he/she tries to delete but not the owner', async function() {
    // Create owner of group
    const owner = await User.create({
      username: 'OWNER',
      password: 'OWNERPASSWORD',
      email: 'OWNEREMAIL@mail.com',
    });
 
    const group = await Group.create({
      ownerId: owner.id,
      name: 'NAME',
      description: 'DESC',
    });
 
    await Membership.create({
      groupId: group.id,
      userId: user.id,
      idAdmin: true,
    });
 
    await agent
        .delete(`/api/group/${group.id}`)
        .set(csrfHeaderName, csrf)
        .expect(401)
        .then((res) => {
          expect(res.body.message).to
              .be.eql(new NotOwnerOfGroupError().message);
        });
  });
 
  it('responses with GroupNotFoundError if user is member of the ' +
      'group, but group doesn\'t exist', async function() {
    // Create owner of group
    const owner = await User.create({
      username: 'OWNER',
      password: 'OWNERPASSWORD',
      email: 'OWNEREMAIL@mail.com',
    });
 
    const group = await Group.create({
      ownerId: owner.id,
      name: 'NAME',
      description: 'DESC',
    });
 
    await Membership.create({
      groupId: group.id,
      userId: user.id,
      idAdmin: true,
    });
 
    // Stub Group.findByPk to simulate that group doesn't exist
    const deleteStub = sinon.stub(GroupService, 'delete')
        .callsFake(() => Promise.reject(new GroupNotFoundError(group.id)));
 
    await agent
        .delete(`/api/group/${group.id}`)
        .set(csrfHeaderName, csrf)
        .expect(404)
        .then((res) => {
          expect(res.body.message).to.include(`Group with id ${group.id}`);
        });
 
    sinon.assert.calledOnce(deleteStub);
  });
 
  it('deletes all memberships with groups and the group and' +
      'responses with 204 if user is owner of group', async function() {
    // Create owner of group
    const group = await Group.create({
      ownerId: user.id,
      name: 'NAME',
      description: 'DESC',
    });
 
    // Create memberships with other users to check
    // if all memberships with that group get deleted
 
    // Create 5 other users
    for (let i = 0; i < 5; i++) {
      const testUser = await User.create({
        username: `test-user-${i}`,
        password: `test-user-${i}`,
        email: `test-user-${i}@mail.com`,
      });
 
      await Membership.create({
        groupId: group.id,
        userId: testUser.id,
        isAdmin: i % 2 === 0,
      });
    }
 
    await agent
        .delete(`/api/group/${group.id}`)
        .set(csrfHeaderName, csrf)
        .expect(204);
 
    // Check if group exists
    expect(await Group.findByPk(group.id)).to.be.null;
 
    // Check if any membership with group exists
    const memberships = await Membership.findAll({where: {groupId: group.id}});
    expect(memberships).to.be.empty;
  });
});