首页 > 解决方案 > JEST:忽略预期错误对象中的制表符/空格

问题描述

在我的测试中,我确切地知道我要断言的输出是什么。但是,我的输出有问题。

当对象相似时,它似乎不处理空白差异。

断言输出以下代码:

    Expected: [Error: Expected path "my_path[0].grandparent.parent" to be found in:
              [
                {
                  "name": "ValidationError",
                  "path": "my_path[0].grandparent.parent.child",
                  "type": "required",
                  "errors": [
                        "error in path two"
                  ],
                  "inner": [],
                  "message": "error in path two",
                  "params": {
                        "path": "my_path[0].grandparent.parent.child"
                  }
                }
              ]]
    Received: [Error: Expected path "my_path[0].grandparent.parent" to be found in:·
     [
        {
            "name": "ValidationError",
            "path": "my_path[0].grandparent.parent.child",
            "type": "required",
            "errors": [
                "error in path two"
            ],
            "inner": [],
            "message": "error in path two",
            "params": {
                "path": "my_path[0].grandparent.parent.child"
            }
        }
    ]]

在测试中我使用“ toEqual ”匹配器

const expectedError = new Error(`Expected path "my_path[0].grandparent.parent" to be found in:
          [
            {
              "name": "ValidationError",
              "path": "my_path[0].grandparent.parent.child",
              "type": "required",
              "errors": [
                    "error in path two"
              ],
              "inner": [],
              "message": "error in path two",
              "params": {
                    "path": "my_path[0].grandparent.parent.child"
              }
            }
          ]`);

it('foobar', () => {
  try {
    // custom expect method which throws an error in this case
    expect({
      my_path: [{ grandparent: { parent: undefined } }],
    }).toBeInvalidWith(schema, required, 'my_path[0].grandparent.parent');
  } catch (error) {
    expect(error).toEqual(expectedError);
  }
});

标签: jestjs

解决方案


问题try..catch是它可能会导致误报,这应该额外处理。

由于它my_path[0].grandparent.parent是相关的部分,因此可以捕获并匹配错误:

  try { 
    ...
    throw new Error('Should not be evaluated');
  } catch (error) {
    expect(error.message).toEqual(
      expect.stringContaining('Expected path "my_path[0].grandparent.parent" to be found in:')
    );
  }

这是高级匹配器的一种情况,例如 jest-extended toThrowWithMessage


推荐阅读