抛出错误时单元测试不通过

时间:2017-11-17 11:48:39

标签: javascript reactjs jest

我有以下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'));

但是,它们都失败并显示相同的错误消息。

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

1 个答案:

答案 0 :(得分:1)

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

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

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