1

I'm getting started with Lab to test my API. The API does the usual CRUD operations and I'm wondering how should I go about testing the Update and Delete methods that require a document ID.

My API returns the newly created mongo document inside response.payload. What I don't understand is why in the DELETE test resultId is undefined.

Here's my code:

lab.experiment('User module', () => {

    var resultId; // Initialize a variable to save the document ID later.

    lab.test('should create user', (done) => {
        var options = {
            method: 'POST',
            url: '/api/v1/users',
            payload: {
                username: 'testUser',
                password: 'testPassword'
            }
        };

        server.inject(options, (response) => {
            resultId = response.payload._id; // Update resultId
            Code.expect(response.statusCode).to.equal(200);
            done();
        });
    });

    lab.test('should delete user', (done) => {
        var options = {
            method: 'DELETE',
            url: '/api/v1/users/' + resultId // Turns out resultId is undefined
        };

        server.inject(options, (response) => {
            Code.expect(response.statusCode).to.equal(200);
            done();
        });
    });

});
Matt Harrison
  • 13,381
  • 6
  • 48
  • 66

1 Answers1

0

If you're running lab with the -p flag, your two test cases will run in parallel. Which means the second test case is evaluating the value of resultId before it's changed by the first test case.

It's bad practice to have a test case rely on another test case changing some common variable. Your test cases should be totally independent from each other. Removing/adding a test case should never break another. This would be a real pain for maintenance.

Make your tests atomic and as separate as possible. Even if it means some repetition. Or you can use lab.beforeEach if you need to set up some common state before each test.

Matt Harrison
  • 13,381
  • 6
  • 48
  • 66
  • I'm not using the `-p` flag, but I see how having a test depend on the result of another is bad. Thanks for pointing that out. However, how should I go about testing those endpoints that require a mongo document to exist? – Silvestre Herrera Nov 13 '15 at 17:20
  • You could mock your database object. Or use a test database with fixtures. – Matt Harrison Nov 13 '15 at 17:46
  • @MattHarrison just a simple example would be greatly appreciated :) – Whisher Nov 14 '15 at 22:15