Skip to content

Instantly share code, notes, and snippets.

@emmsdan
Last active March 20, 2019 01:19
Show Gist options
  • Save emmsdan/675d1799df451b21823dc6a8b4cdacc9 to your computer and use it in GitHub Desktop.
Save emmsdan/675d1799df451b21823dc6a8b4cdacc9 to your computer and use it in GitHub Desktop.
test if a user already exists
import chai from 'chai';
import chaiHttp from "chai-http";
import { app as server } from './app.js';
// configure chai to send/receive HTTP REQUEST
chai.use(chaiHttp);
describe("TDD for Users", () => {
after(() => {
server.close();
});
context("Check if a User already Exist", () => {
it("username should exist", (done) => {
chai.request(server)
.get('api/v1/getuser/emmsdan')
.end((error, response) => {
response.should.be.status(200);
response.should.be.an('object');
done();
})
})
it("user should not exist", (done) => {
chai.request(appServer)
.get('api/v1/getuser/fakename')
.end((error, response) => {
response.should.be.status(404);
response.should.be.an('string');
done();
})
})
})
})
@nwamugo
Copy link

nwamugo commented Mar 19, 2019

@emmsdan good output.

  • I usually use three verbs... describe, context, it

describe to highlight the file/module in which we are testing
context for each function that is being tested
it for each expectation that is being tested.

  • In the overall describe containing arrow function, that is a good place to put after() function perhaps to close the server after tests.

Kindly take a look at my own gist, and drop any feedback you may have https://gist.github.com/nwamugo/14a5a8e21beb481b86df93b7a5fb7ee5

Cheers!

@emmsdan
Copy link
Author

emmsdan commented Mar 19, 2019

Thank you for that,
for readability using context in a describe block is better than using a describe in a describe.

@NedyUdombat
Copy link

Simple and straight-forward test.
Do you mind checking your grammatical construction the test descriptions?

@igbominadeveloper
Copy link

igbominadeveloper commented Mar 20, 2019

Simple and neatly constructed. Noticed a few things:

  • When using the it method, it would help if the string you pass into it is easily readable for the developer(s) who will be reading the test descriptions to know what it does. A sample snippet for clarity:

describe('TDD for users')

it('should return a 200 response if user already exists')
it('should return a 404 response if user does not exist')

I think my example seems a little wordy though.

  • In the second case, you asserted that the response returned by chai should be a string but it always returns an object like you did in case 1. I think you wanted to drill down to response.body

  • Eslint flags accepting a variable or argument you end up not using in your code. e.g. in the end statements, you could prefix the error objects with an underscore i.e. _error.

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