vendredi 13 novembre 2015

Testing Hapijs API with Lab

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();
        });
    });

});

Aucun commentaire:

Enregistrer un commentaire