Javascript 使用Mocha和x2B进行单元测试;PhantomJS异步代码

Javascript 使用Mocha和x2B进行单元测试;PhantomJS异步代码,javascript,unit-testing,mocha.js,chai,mocha-phantomjs,Javascript,Unit Testing,Mocha.js,Chai,Mocha Phantomjs,我是单元测试新手,所以如果我的问题很愚蠢,请告诉我。我使用带有PhantomJS和Chai的Mocha作为断言库编写了一个单元测试。我要测试的代码是以下函数: function speakingNotification(audioStream){ var options = {}; var speechEvents = hark(audioStream, options); speechEvents.on('speaking', function() { return 's

我是单元测试新手,所以如果我的问题很愚蠢,请告诉我。我使用带有PhantomJS和Chai的Mocha作为断言库编写了一个单元测试。我要测试的代码是以下函数:

function speakingNotification(audioStream){
  var options = {};
  var speechEvents = hark(audioStream, options);

  speechEvents.on('speaking', function() {
    return 'speaking';
  });

  speechEvents.on('stopped_speaking', function() {
    return 'stopped_speaking';
  });
}
正如您所见,它将audioStream参数作为输入,然后使用名为hark.js的库来检测讲话事件。如果用户正在说话或不说话,该函数应返回

因此,我编写了以下单元测试:

describe('Testing speaking notification', function () {
    describe('Sender', function(){

        var audio = document.createElement('audio');
        audio.src = 'data:audio/mp3;base64,//OkVA...'; //audio file with sound

        var noAudio = document.createElement('audio');
        noAudio.src = 'data:audio/mp3;base64,...';  //audio file with no sound

        it('should have a function named "speakingNotification"', function() {
            expect(speakingNotification).to.be.a('function');
        });

        it('speaking event', function () {
            var a = speakingNotification(audio);
            this.timeout( 10000 );
            expect(a).to.equal('speaking');
        });

        it('stoppedSpeaking event', function () {
            var a = speakingNotification(noAudio);
            this.timeout( 10000 );
            expect(a).to.equal('stopped_speaking');
        });

    });
});
测试失败并显示:

 AssertionError: expected undefined to equal 'speaking'

 AssertionError: expected undefined to equal 'stopped_speaking'
ReferenceError: Can't find variable: done
我还尝试使用done()代替超时,但是测试失败并显示:

 AssertionError: expected undefined to equal 'speaking'

 AssertionError: expected undefined to equal 'stopped_speaking'
ReferenceError: Can't find variable: done
我搜索了一些教程,但是我只能找到一些没有帮助的简单例子。
如何编写正确的测试?

您在这里向我们展示的问题可能与您在第一个代码段中如何编写代码有关。如果你读了另一个问题的答案,你就会知道你做错了什么。