简体   繁体   中英

Why is Mocha passing this https.get request?

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

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM