0

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

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 https://github.com/otalk/hark的库来检测说话事件。如果用户正在讲话,该函数应该返回。

所以我写了以下单元测试:

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'

我也尝试使用 done() 设置超时,但是测试失败并显示:

ReferenceError: Can't find variable: done

我搜索了教程,但是我只能找到没有帮助的简单示例。如何编写正确的测试?

4

0 回答 0