0

Brand new to testing. Trying to figure out why mocha is passing this test when it should be failing.

var assert     = require('assert');
var nock       = require('nock');
var https      = require('https');

describe('thing', function() {
    describe('foo', function () {
        it('makes the correct https call to API', function () {
            nock('https://example.com')
                .get('/foo')
                .reply(404);
            https.get('https://example.com/foo', function (response) {
                console.log(response.statusCode); // returns 404
                assert.equal(response.statusCode, 200); //passes
            });
        });
    });
});

enter image description here

brandonscript
  • 68,675
  • 32
  • 163
  • 220
Blexy
  • 9,573
  • 6
  • 42
  • 55

1 Answers1

2

Mocha, just like any other [properly-written] Node.js module/app, runs asynchronously out of the box. Because your https call takes longer to execute than the entire Mocha test, Mocha never has a chance to perform its assertions before the process completes.

That said, Mocha tests also supports a callback that let you execute long-running activities before performing your assertions:

var assert     = require('assert');
var nock       = require('nock');
var https      = require('https');

describe('thing', function() {
    describe('foo', function () {
        it('makes the correct https call to API', function (done) {
            nock('https://example.com')
                .get('/foo')
                .reply(404);
            https.get('https://example.com/foo', function (response) {
                console.log(response.statusCode); // returns 404
                assert.equal(response.statusCode, 200); //passes
                done();
            });
        });
    });
});
brandonscript
  • 68,675
  • 32
  • 163
  • 220