Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 抛出错误时,单元测试未通过_Javascript_Reactjs_Jestjs - Fatal编程技术网

Javascript 抛出错误时,单元测试未通过

Javascript 抛出错误时,单元测试未通过,javascript,reactjs,jestjs,Javascript,Reactjs,Jestjs,我有以下JS类: class MyDispatcher { subscribe(eventName, handler) { if (typeof eventName !== 'string') { throw new Error('eventName must be a string'); } //some other code } } 我有一个Jest单元测试: test('Non string event fails', () =>

我有以下JS类:

class MyDispatcher {

  subscribe(eventName, handler) {

    if (typeof eventName !== 'string') {
        throw new Error('eventName must be a string');
    }

   //some other code
  }

}
我有一个Jest单元测试:

test('Non string event fails', () => {
    expect(MyDispatcher.subscribe(3, 'myHandler')).toThrow();
});
问题是,当我运行测试时,它失败并出现以下错误:

● myDispatcher › Non string event fails

    eventName must be a string

      at MyDispatcher.subscribe (src/modules/MyDispatcher.js:10:7)
      at Object.<anonymous> (src/modules/__tests__/MyDispatcherTest.js:26:31)
这个测试:

expect(MyDispatcher.subscribe(3, 'myHandler')).toThrowError('eventName must be a string');
expect(MyDispatcher.subscribe(3, 'myHandler')).toThrow(new Error('eventName must be a string'));
但是,它们都会失败,并显示相同的错误消息


知道这些测试失败的原因吗?

在执行实际测试之前,
MyDispatcher.subscribe(3,'myHandler')
函数调用会引发异常,请替换

expect(MyDispatcher.subscribe(3, 'myHandler')).toThrow();


这就是重点。我希望输入是错误的,这样我就可以抛出一个错误。
expect(() => MyDispatcher.subscribe(3, 'myHandler')).toThrow();