search

Home  >  Q&A  >  body text

mocha - Node.js下异步调用失效

业务代码如下:

"use strict";

var request = require('request')

var A = function () {
    this.a = function () {
        var op = {
            url: 'www.test.com'
            ...
        }
        request(op, function(err, res, data){
            console.log('request OK')
            console.log(data);
        })

    }
};

module.exports = A;

对应的单元测试代码如下:

var should = require('chai').should();
var A = require('../../lib/A');

var test = new A();

describe('A test', function () {
    it('test', function () {
        test.a();
    })
});

我期望它应该能够输出request OK和data,但是实际上mocha在进行单元测试的时候没有任何输出就直接通过了。
这里的异步调用为什么没有正常进行呢?


mocha参数为mocha --recursive

ringa_leeringa_lee2785 days ago686

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 15:25:53

    Thank you for the invitation.

    A.a();According to what you mean, it should be test.a();

    Explain that before the constructor is instantiated, its own properties are the private properties of the function object and cannot be accessed from the outside.


    Update

    This is an asynchronous test case, add a timeout setting or impose a callback.

    --recursive This parameter is only used to recursively execute subtests in the current directory

    mocha -t 10000 test.js

    or

    describe('A test', function () {
        it('test', function (done) {
            test.a(function(){
                done();
             });
        })
    });
    
    // A function
        this.a = function (cb) {
            var op = {
                url: 'www.test.com'
                ...
            }
            request(op, function(err, res, data){
                console.log('request OK')
                console.log(data);
                if(typeof cb === 'function') cb();
            })
    
        }

    reply
    0
  • 阿神

    阿神2017-04-17 15:25:53

    If I remember correctly, the most test cases for mocha are 2000ms. When testing asynchronous examples, try adding -t and -timeout. A student rarely writes unit tests. . .

    reply
    0
  • Cancelreply