单元测试语音识别API

时间:2014-09-09 21:43:50

标签: javascript google-chrome testing webkit speech-recognition

webkitSpeechRecognition api非常适合单元测试

如果我想测试api,我似乎必须在浏览器中说话。是否有人知道测试使用此API的工作流程的其他方法?

1 个答案:

答案 0 :(得分:0)

尝试使用模拟对象替换浏览器的SpeechRecognition对象的corti。此对象复制(大多数)本机功能,并为其添加一些其他辅助方法以简化测试(例如say()方法 模拟语音输入。)

以下是Corti的一些示例代码:

// Patch the current environment with a mock Speech Recognition object
Corti.patch();

// Interact with the mock object, like with the real SpeechRecognition object
var recognition = new window.SpeechRecognition();
recognition.onstart = function() {console.log("I'm listening");};
recognition.addEventListener('result', function(sre) {
  console.log(sre.results.item(sre.resultIndex).item(0).transcript);
});
recognition.addEventListener('end', function() {console.log("Quiet");});
recognition.continuous = true;

// Use extra utility methods added to the mock object to assist with testing
expect(recognition.isStarted()).toBe(false);
recognition.start();
expect(recognition.isStarted()).toBe(true);
recognition.abort();
expect(recognition.isStarted()).toBe(false);

// Simulate speech recognition
recognition.addEventListener('result', mySpyFunction);
expect(mySpyFunction).not.toHaveBeenCalled();
recognition.say("Next time you want to stab me in the back, have the guts to do it to my face");
expect(mySpyFunction).toHaveBeenCalled();
相关问题