I am trying to test protected routes with multiple users (I'll check later resources authorisations) It' s fine when I start testing with one user , setting & saving the user in the before() hook, but as soon as I set and save a second user in this hook , then all my tests are not passing... It seems the second user setup is changing something with JWT .. ?
const rootUser = new User({
username: config.mongo.user,
password: config.mongo.pwd,
email: 'johndoe@example.com',
mobileNumber: 123456789
});
let rootJwtToken = '';
/**
* root level hooks
*/
before(() =>
rootUser.save({})
.then((savedRootUser) => {
const rootToken = jwt.sign({ username: savedRootUser.username }, config.jwtSecret);
rootJwtToken = `Bearer ${rootToken}`;
})
);
after(() => {
User.remove(() => {});
Group.remove(() => {});
// required because https://github.com/Automattic/mongoose/issues/1251#issuecomment-65793092
mongoose.models = {};
mongoose.modelSchemas = {};
mongoose.connection.close();
});
describe('## root user w Group APIs', () => {
let group = {
name: 'Admin',
description: 'Administration group'
};
describe('# POST /api/v1/groups', () => {
it('should allow root user to create a new group', () =>
request(app)
.post('/api/v1/groups')
.set('Authorization', rootJwtToken)
.send(group)
.expect(httpStatus.OK)
.then((res) => {
// check group
expect(res.body.name).to.equal(group.name);
expect(res.body.description).to.equal(group.description);
group = res.body;
})
);
});
describe('# DELETE /api/v1/groups/:groupId', () => {
it('should allow root user to delete a group', () =>
request(app)
.delete(`/api/v1/groups/${group._id}`)
.set('Authorization', rootJwtToken)
.expect(httpStatus.OK)
.then((res) => {
expect(res.body.name).to.equal('Administrator');
})
);
});
});
Then I test after adding another user
const rootUser = new User({
username: config.mongo.user,
password: config.mongo.pwd,
email: 'johndoe@example.com',
mobileNumber: 123456789
});
let rootJwtToken = '';
const adminUser = new User({
username: cadminuser',
password: '999999999,
email: 'william@example.com',
mobileNumber: 97654321
});
let adminwtToken = '';
/**
* root level hooks
*/
before(() => {
rootUser.save({})
.then((savedRootUser) => {
const rootToken = jwt.sign({ username: savedRootUser.username }, config.jwtSecret);
rootJwtToken = `Bearer ${rootToken}`;
});
adminUser.save({})
.then((savedAdminUser) => {
const adminToken = jwt.sign({ username: savedAdminUser.username }, config.jwtSecret);
adminJwtToken = `Bearer ${adminToken}`;
});
});
....
describe('## root user w Group APIs', () => {
...using rootJwtToken
}
describe('## admin user w Group APIs', () => {
...using adminJwtToken
}
thanks for your feedbacks
via erwin
No comments:
Post a Comment