Skip to content

Instantly share code, notes, and snippets.

@chukwuemekachm
Created July 23, 2018 13:38
Show Gist options
  • Save chukwuemekachm/006919e128e3d02af5046badabf5257c to your computer and use it in GitHub Desktop.
Save chukwuemekachm/006919e128e3d02af5046badabf5257c to your computer and use it in GitHub Desktop.
This is a single TDD test using mocha, chai and chai-http. The test tests that the user's token is valid and returns an Invalid auth token response.
// import describe and it from mocha as named exports
import { describe, it } from 'mocha';
// import chai and chai-http from chai and chai-http libraries as default exports
import chai from 'chai';
import chaiHttp from 'chai-http';
// import server from index.js as default export
import server from '../../index';
/*
* initialise chai to use chai-http
* initialise should as the assertion type
*/
chai.use(chaiHttp);
chai.should();
// General describe block
describe('GET /users', () => {
// when an unauthorized user tries to get a profile
it('should return 401, when access token is invalid', (done) => {
chai.request(server).get('/api/users')
.set('Authorization', 'Bearer badToken623bewq842j3kr')
.end((req, res) => {
res.should.have.status(401);
res.body.should.be.a('object');
res.body.should.have.property('status');
res.body.status.should.eql('fail');
res.body.should.have.property('errors');
res.body.errors.should.be.a('object');
res.body.errors.should.have.property('body');
res.body.errors.body.should.be.a('array');
res.body.errors.body.should.include('Invalid authorization token');
done();
});
});
});
@yomigeek
Copy link

Well documented test code, and good code structure...

@Oluwafayokemi
Copy link

Oluwafayokemi commented Jul 23, 2018

Good job, your tests cases are well structured. You might not want to only know when there is an error with the code. You would want to affirm when there is no error. Writing a test for the success could also be fine.

@Veraclins
Copy link

Nice work Chima. You might want to change your comment on the code as getting a profile uses a different route '/api/profiles/:username' and does not require authentication. I think 'when an unauthorized user tries to access the user route' could be a better description.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment