【问题标题】:Testing Failure: ReferenceError: SpeechSynthesisUtterance is not defined测试失败:ReferenceError:未定义 SpeechSynthesisUtterance
【发布时间】:2018-05-05 22:59:37
【问题描述】:

我最近尝试在我的项目中实现文本到语音,并决定使用纯 JavaScript 解决方案。 (https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance)

我目前正在使用 React@15.4.2 和酶@2.9.1。

代码:

export default class DummyComponent extends React.Component {
    /* */
    speak(text) {
        var synth = window.speechSynthesis;
        var utterThis = new SpeechSynthesisUtterance(text);
        synth.speak(utterThis);
    }
    /* */
}

一切正常,但每当我尝试测试我的代码时,标题中都会出现错误。

示例测试:

it('dummytest', function(done){
    const prop1 = 'foo';
    const prop2 = 'bar';
    const wrapper = shallow(<DummyComponent prop1 = {foo} prop2={bar}/>);
    expect(wrapper.html()).to.include("foobar");
    done(); 
});

ReferenceError: SpeechSynthesisUtterance 未定义

不管我在这个类中测试什么,我对这个组件的所有测试都失败了,因为 Enzyme 方法很浅,mount 和 render 不知道 SpeechSynthesisUtterance。 p>

SpeechSynthesisUtterance 实际上来自 typescript 库。 (typescript/lib/lib.es6.d.ts)

我已经尝试过的事情:

  • 将 Enzyme 升级到 3.2(产生完全相同的错误)
  • 导出函数
  • 使用 tsconfig 文件编译 lib.es6.d.ts

对于后者,我尝试了一系列不同的设置,并尝试在文件顶部添加“export {}”。这实际上引发了这个错误:

node_modules/typescript/lib/lib.es6.d.ts(5769,15):错误 TS2470:“符号”引用未引用全局符号构造函数对象。

我没有使用 typescript 的经验,所以我想不出下一步该尝试什么。

【问题讨论】:

    标签: javascript node.js reactjs typescript enzyme


    【解决方案1】:

    Typescript 具有接口定义,因为该函数是 global 在浏览器中(检查 chrome 和 firefox),因此您可以引用它。但是对于节点环境不是全局的,这就是你的测试失败的原因,你应该导入它来测试它,但我不认为这是可用的,所以如果你想测试也许你可以为函数创建一个存根版本

    【讨论】:

    【解决方案2】:

    这个问题的答案,因为谷歌把我带到这里并且没有修复......

    问题在于SpeechSynthesisUtterance 是实验性技术,因此并非所有地方都支持它。您的测试套件不支持它,some browsers 也不支持。

    检查代码中是否存在 API。

    if(window['speechSynthesis'] === undefined) {
        return; // Bail out
    }
    

    if ('speechSynthesis' in window) {
        // Do something with Speech
    }
    

    在这种情况下:

    export default class DummyComponent extends React.Component {
        /* */
        speak(text) {
            if(window['speechSynthesis'] === undefined) {
                return;
            }
    
            var synth = window.speechSynthesis;
            var utterThis = new SpeechSynthesisUtterance(text);
            synth.speak(utterThis);
        }
        /* */
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-12
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      • 2022-12-05
      • 2018-02-26
      • 2019-09-25
      • 1970-01-01
      相关资源
      最近更新 更多