mocha - Node.js下异步调用失效
ringa_lee
ringa_lee 2017-04-17 15:23:53
0
2
625

业务代码如下:

"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_lee
ringa_lee

ringa_lee

reply all(2)
Peter_Zhu

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

    }
阿神

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. . .

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!