Add role middleware tests

This commit is contained in:
Elliot DeNolf
2019-01-04 02:19:26 -05:00
parent 7bd4bda08e
commit 83524bc25a
4 changed files with 1058 additions and 24 deletions

View File

@@ -0,0 +1,109 @@
import middleware from '../middleware';
import mockExpress from 'jest-mock-express';
let res = null;
let next = null;
beforeEach(() => {
res = mockExpress.response();
next = jest.fn();
});
describe('Payload Role Middleware', () => {
it('Exact role - authorized', () => {
const req = {
user: {
role: 'user'
}
};
middleware.role('user')(req, res, next);
expect(next.mock.calls.length).toBe(1);
expect(res.status).not.toHaveBeenCalled();
});
it('Exact role - unauthorized', () => {
const req = {
user: {
role: 'user'
}
};
middleware.role('admin')(req, res, next);
expect(next.mock.calls.length).toBe(0);
expect(res.status).toHaveBeenCalled();
expect(res.send).toHaveBeenCalled();
});
it('At least role - exact', () => {
const roleList = [
'admin',
'user',
'viewer'
];
const req = {
user: {
role: 'user'
}
};
middleware.atLeastRole(roleList, 'user')(req, res, next);
expect(next.mock.calls.length).toBe(1);
});
it('At least role - permitted', () => {
const roleList = [
'admin',
'user',
'viewer'
];
const req = {
user: {
role: 'user'
}
};
middleware.atLeastRole(roleList, 'viewer')(req, res, next);
expect(next.mock.calls.length).toBe(1);
});
it('At least role - unauthorized', () => {
const roleList = [
'admin',
'user',
'viewer'
];
const req = {
user: {
role: 'user'
}
};
middleware.atLeastRole(roleList, 'admin')(req, res, next);
expect(next.mock.calls.length).toBe(0);
expect(res.status).toHaveBeenCalledWith(401);
});
it('At least role - non-existent role', () => {
const roleList = [
'admin',
'user',
'viewer'
];
const req = {
user: {
role: 'user'
}
};
middleware.atLeastRole(roleList, 'invalid')(req, res, next);
expect(next.mock.calls.length).toBe(0);
expect(res.status).toHaveBeenCalledWith(500);
})
});