Skip to content

Instantly share code, notes, and snippets.

@markterence
Created July 9, 2019 05:04
Show Gist options
  • Save markterence/ab1113cd277baed9701370e008c3df14 to your computer and use it in GitHub Desktop.
Save markterence/ab1113cd277baed9701370e008c3df14 to your computer and use it in GitHub Desktop.
UserController Test using supertest, mocha, and jest's matchers.
const request = require('supertest');
const expect = require('expect');
describe('User Controller', () => {
var user;
before(async () => {
await Users.create({
username: 'testuser1',
password: 'testuser1',
email: 'testuser@email.com'
});
user = await LoginServiceAPIv2.passwordLogin({
username: 'testuser1',
password: 'testuser1'
});
});
describe('POST /api/users', () => {
it('should return an error message because the email field is empty', async () => {
return request(sails.hooks.http.app)
.post('/api/users')
.set('Authorization', `Bearer ${user.token}`)
.send({
username: 'testuser1',
password: 'testuser2'
})
.expect(400)
.then(res => {
expect(res.body).toContainAllKeys(['email']);
expect(res.body).not.toContainKeys(['username', 'password']);
});
});
it('should return an error message because the "password" field is empty', async () => {
return request(sails.hooks.http.app)
.post('/api/users')
.set('Authorization', `Bearer ${user.token}`)
.send({
username: 'testuser2',
email: 'email@testuser1.com'
})
.expect(400)
.then(res => {
expect(res.body).toContainAllKeys(['password']);
expect(res.body).not.toContainKey('username');
});
});
it('should return an error message because the "username" is invalid', async () => {
return request(sails.hooks.http.app)
.post('/api/users')
.set('Authorization', `Bearer ${user.token}`)
.send({
username: '.testuser2.',
email: 'email@testuser1.com'
})
.expect(400)
.then(res => {
expect(res.body).toContainAllKeys(['username']);
expect(res.body).not.toContainKey('email');
});
});
});
describe('GET /api/users', () => {
it('the table should have a record related to "testuser1"', async () => {
return request(sails.hooks.http.app)
.get('/api/users')
.set('Authorization', `Bearer ${user.token}`)
.then(res => {
expect(res.body).toMatchObject(expect.any(Array));
expect(res.body).toContainEqual(
expect.objectContaining({ username: 'testuser1' })
);
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment