webkitSpeechRecognition API 很大程度上是单元测试的黑盒
如果我想测试 API,我必须与浏览器对话。有谁知道测试使用此 api 的工作流程的替代方法吗?
尝试 Corti,它用模拟对象替换浏览器的 SpeechRecognition (或 webkitSpeechRecognition)。
语音识别 API 的模拟复制了本机功能,并添加了一些其他有用的方法,使自动化测试变得更容易(例如,以编程方式模拟语音输入的
say()
方法)。
您可以通过以下方式安装它:
npm install corti
安装后,您可以在任何测试框架、Node.js 或浏览器中编写的测试中使用它。
import { SpeechRecognition } from 'corti';
import { describe, it, expect, beforeEach, beforeAll, afterAll, vi } from 'vitest';
beforeAll(() => {
vi.stubGlobal('SpeechRecognition', SpeechRecognition);
});
afterAll(() => {
vi.unstubAllGlobals();
});
describe('Mirror mirror on the wall', () => {
let recognition;
let spyFn;
beforeEach(() => {
recognition = new globalThis.SpeechRecognition();
spyFn = vi.fn();
recognition.maxAlternatives = 5;
recognition.onresult = spyFn;
recognition.start();
});
it('should call callback when called with a single sentence', () => {
recognition.say('Hello world');
expect(spyFn).toHaveBeenCalled();
const event = spyFn.mock.calls[0][0];
expect(event.results[0][0].transcript).toBe('Hello world');
});
it('should call callback when called with multiple sentences', () => {
recognition.say(['Hello world', 'How are you?']);
expect(spyFn).toHaveBeenCalled();
const event = spyFn.mock.calls[0][0];
expect(event.results[0][0].transcript).toBe('Hello world');
expect(event.results[0][1].transcript).toBe('How are you?');
});
});
const { SpeechRecognition } = require('corti');
beforeAll(() => {
global.SpeechRecognition = SpeechRecognition;
});
test('SpeechRecognition', () => {
const speech = new globalThis.SpeechRecognition();
const spyFn = jest.fn();
speech.onresult = spyFn;
speech.continuous = true;
speech.start();
speech.say('Hello world');
speech.say('Hello world');
expect(spyFn.mock.calls.length).toBe(2);
});