【问题标题】:How can I test error handing without try-- catch如何在没有 try--catch 的情况下测试错误处理
【发布时间】:2019-04-29 16:35:00
【问题描述】:

我正在编写验证文本的代码。这就是我测试它的方式。但我不想在单元测试中使用 try--catch 。请给我一个更好的方法。

it('Testing if hook errors on invalid description.', async () => {
      try {
        workRequest.requestor = 'John';
        workRequest.description = 1;
        result = await app.service('dummy').create(workRequest);
      } catch (error) {
        assert.equal(error.errors.description, 'Description is must be a string');
      }
    });

【问题讨论】:

    标签: javascript node.js unit-testing mocha.js


    【解决方案1】:

    你要找的是这样的东西 should.throws 几乎所有的测试框架都支持这个 API

    例如:

    应该

    https://shouldjs.github.io/#should-throws

    摩卡

    https://mochajs.org/#bdd

    还有

    https://nodejs.org/api/assert.html#assert_assert_throws_fn_error_message

     it('Testing if hook errors on invalid description.', async () => {
            assert.throws(  () =>  {
                workRequest.requestor = 'John';
                workRequest.description = 1;
                result = await app.service('dummy').create(workRequest);
            },
      err 
    );
    

    【讨论】:

    • 我不是 JavaScript 专家,但我从未见过这样的代码块传递语法,不一定是 () => { ... } 而不是 { ... }
    • 你是对的,谢谢@Matthew。我更新了我的代码
    • 我怎么知道它发送了正确的错误信息?因为我需要验证多元素
    • 只需将预期对象传递给 err 参数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 2012-11-15
    • 2016-08-18
    • 2011-08-25
    • 2021-11-11
    相关资源
    最近更新 更多