我有一些使用
AudioContext
注入服务的组件,比如
`my service constructor`
constructor() {
this.context = new AudioContext();
}
但是笑话一直告诉我
AudioContext is not defined
我看过其他答案,但大多数时候
AudioContext
作为参数传递,在我的例子中,这是在依赖项内实例化的。
JSDOM 目前不支持 WebAudio 规范。
解决方案是创建模拟
AudioContext
并将其放入 setupFile 中。
例如
index.ts
:
export function main() {
const context = new AudioContext();
context.createOscillator();
context.createGain();
return context;
}
index.test.ts
:
import { main } from '.';
describe('78023642', () => {
test('should pass', () => {
const context = main();
expect(context).toBeDefined();
});
});
jest.setup.js
:
class AudioContextMock {
createOscillator() {}
createGain() {}
}
global.AudioContext = AudioContextMock;
jest.config.js
:
module.exports = {
testEnvironment: 'jsdom',
setupFiles: ['<rootDir>/jest.setup.js'],
};
测试结果:
PASS stackoverflow/78023642/index.test.ts
78023642
√ should pass (1 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.753 s, estimated 1 s
Ran all test suites related to changed files.
封装版本:
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",