【发布时间】:2019-09-01 02:56:55
【问题描述】:
我在尝试对使用 AudioContext 的类进行一些测试时遇到了很多麻烦。我相信我的很多挫败感源于对模拟函数以及可能如何执行测试没有很好的理解。
我正在尝试测试一个使用 AudioContext 的类,但是当我运行测试时我不断收到此错误:
使用 TypeScript 文件时:
TypeError: (window.AudioContext || window.webkitAudioContext) 不是构造函数
此错误发生在 app.ts 文件中。当我运行测试时,它是否必须解析或执行它的所有依赖项?
使用 JavaScript 文件时,测试文件中会出现此错误:ReferenceError: AudioContext is not defined
现在,我假设我必须制作一个模拟 AudioContext。我什至如何了解 AudioContext 上的所有方法才能开始手动模拟它?
这是我的工作表的简化版本。我将提供两者的 TS 和 JS 版本:
TypeScript 文件版本:
// app.ts
import Sampler from './Sampler';
const audioContext: AudioContext = new (window.AudioContext || window.webkitAudioContext)();
const sampler: Sampler = new Sampler(audioContext);
// Sampler.ts
export default class Sampler{
private audioContext: AudioContext;
constructor(audioContext: AudioContext){
this.audioContext = audioContext;
}
}
JS 文件版本:
// app.js
const Sampler = require('./Sampler');
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const sampler = new Sampler(audioContext);
// Sampler.js
class Sampler{
constructor(audioContext){
this.audioContext = audioContext;
}
}
module.exports = Sampler;
测试文件以粗体显示我之前提到的错误:
// sampler.test.ts
import Sampler from './Sampler';
// Uncomment line below if you're using plain JS and not TS
// const Sampler = require('./Sampler');
test('Test test', () => {
const audioContext = new AudioContext();
const s = new Sampler(audioContext);
})
更新: 我现在有适用于纯 JS 文件的代码。我在测试中添加了一个空的 AudioContext 模拟。
// sampler.test.js
const Sampler = require('./Sampler');
require('./__mocks__/app');
test('Testing Mock AudioContext', () => {
const audioContext = new AudioContext();
const s = new Sampler(audioContext);
})
// __mocks__/app.js
window.AudioContext = jest.fn().mockImplementation(() => {
return {}
});
由于我的项目是用 TypeScript 编写的,所以我尝试将模拟添加到我的项目中,但我仍然收到上面的错误“TypeError: (window.AudioContext || window.webkitAudioContext) is not a constructor”。
谢谢:)。
【问题讨论】:
标签: javascript typescript unit-testing testing jestjs