Search code examples
node.jsunit-testingmocha.jssupertestmern

Mocha test with SuperTest always passes (even when wrong)


I'm using Mocha and SuperTest to test my Express API. However my first test always seems to pass when inside the .then() of my request().

I'm passing in a String to a test that is expecting an Array. So should definitely fail the test.

It fails outside of the then() as expected, but I won't have access to the res.body there to perform my tests.

Here is my code:

const expect = require('chai').expect;
const request = require('supertest');

const router = require('../../routes/api/playlist.route');
const app = require('../../app');

describe('Playlist Route', function() {
    // before((done) => {

    // }
    describe('Get all playlists by user', function() {
        it('Should error out with "No playlists found" if there are no Playlists', function() {
            request(app).get('/api/playlists/all')
                .then(res => {
                    const { body } = res;

                    // Test passes if expect here
                    expect('sdfb').to.be.an('array'); 
                })
                .catch(err => {
                    console.log('err: ', err);
                });
            // Test fails if expect here
            expect('sdfb').to.be.an('array'); 
        })
    })
});

I found this article but I'm not using a try catch block, but I thought maybe it could have something to do with the promise.


Solution

  • Quick reponse

    it('decription', function(done) {
        asyncFunc()
            .then(() => {
                expect(something).to.be(somethingElse)
                done()
            })
    })
    

    Detailed response in the comment of @jonrsharpe