【问题标题】:Make a jest test to fail on any error thrown?在抛出任何错误时进行开玩笑测试以失败?
【发布时间】:2019-07-01 10:16:42
【问题描述】:

如果抛出任何错误,我怎样才能使开玩笑测试失败?

我已经尝试了一些,但还没有确定语法。

test('getArcId => Error', async () => {
    await expect(client.getArcId('skynet')).rejects.toThrow();
});

我收到错误消息

getArcId › getArcId => 错误

expect(received).rejects.toThrow()

接收到的函数没有抛出

但是以下测试通过了,所以我打算测试的函数确实会抛出(至少就我对抛出的含义的理解而言):

test('getArcId => Error', async () => {
    await client.getArcId('skynet').catch(e => 
        expect(e.message).toBe('Command failure')
    );
});

【问题讨论】:

  • 在标题中,它说“抛出任何错误都失败”,而对于代码,它似乎在抛出 NO 错误时失败。
  • 稍后我会更多地查看文档,看看我是否误解了某些内容。我希望在 promise 被拒绝时测试成功。

标签: typescript unit-testing error-handling jestjs


【解决方案1】:

检查函数抛出的错误

it('should return error message', () => {
    expect(() => fn().toThrowError(
        new Error('Error Message')
    );
});

【讨论】:

    【解决方案2】:
    describe('getArcId()', () => {
      it('should throw an error', async () => {
        try {
          await client.getArcId('skynet');
        } catch (e) {
          expect(e).toStrictEqual(Error('No command provided to proxy.'));
        }
      });
    });
    

    【讨论】:

    • 简短的纯代码答案在 Stack Overflow 上经常不受欢迎。为了避免(再次)被标记为“低质量”,请添加一些解释性文字。
    【解决方案3】:

    我无法让toThrow() 工作,但像这样进行测试确实有效;

    it('throws on connection error', async () => {
        expect.assertions(1);
        await expect(nc.exec({ logger: true }))
        .rejects.toEqual(Error('No command provided to proxy.'));
    });
    

    如果我只拒绝一条消息;

    .rejects.toEqual('some message');
    

    【讨论】:

    • Ughhh .. 我花了很长时间才让它工作。你的回答很快就解决了。
    【解决方案4】:

    要让 Jest 异常处理按预期工作,请传递一个匿名函数,例如:

    test('getArcId => Error', async () => {
        await expect(() => client.getArcId('skynet')).rejects.toThrow();
    });
    

    来自jest documentation

    test('throws on octopus', () => {
      expect(() => {
        drinkFlavor('octopus');
      }).toThrow();
    });
    

    请注意匿名函数。是的,这让我有好几次:)

    【讨论】:

    • 使用你的建议,我得到:“匹配器错误:接收到的值必须是一个承诺,接收到的类型:函数,接收到的值:[函数匿名]”
    • 使匿名函数异步没有帮助。
    • return expect(....).rejects.toThrow();为我工作。没有“.rejects”。在 expect 里面是一个 Promise 被拒绝
    猜你喜欢
    • 1970-01-01
    • 2018-09-27
    • 2020-03-11
    • 2018-02-13
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    相关资源
    最近更新 更多