如何捕获JavaScript中的断言错误?

时间:2019-02-08 22:37:08

标签: javascript jasmine

将try / catch块与期望一起使用时,如果期望失败,则不会捕获错误。有什么办法可以捕获javascript中的断言错误?代码示例:

try {

     expect(2).toBe(3);

    } catch ( error) {

       console.log(error);
    }

1 个答案:

答案 0 :(得分:0)

您可以创建一个 custom matcher

例如

const customMatchers = {
  toBeWithThrow(matchersUtil) {
    return {
      compare: function (actual, expected) {
        const result = {};
        result.pass = matchersUtil.equals(actual, expected);
        if (result.pass) {
          result.message = 'Expected ' + actual + ' to be ' + expected;
        } else {
          throw new Error('Expected ' + actual + ' to be ' + expected);
        }
        return result;
      },
    };
  },
};

describe('54601177', () => {
  beforeEach(function () {
    jasmine.addMatchers(customMatchers);
  });
  it('should pass', () => {
    expect(2).toBeWithThrow(2);
  });
  it('should pass too', () => {
    try {
      expect(2).toBeWithThrow(3);
    } catch (error) {
      console.log(error);
    }
  });
});

测试结果:

Executing 2 defined specs...
Running in random order... (seed: 09363)

Test Suites & Specs:

1. 54601177
⠋    should pass tooError: Expected 2 to be 3
    at compare (/Users/ldu020/workspace/github.com/mrdulin/jasmine-examples/src/stackoverflow/54601177/index.test.js:10:17)
    at Expector.compare (/Users/ldu020/workspace/github.com/mrdulin/jasmine-examples/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:3969:27)
    at Expectation.toBeWithThrow (/Users/ldu020/workspace/github.com/mrdulin/jasmine-examples/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:3659:34)
    at UserContext.<anonymous> (/Users/ldu020/workspace/github.com/mrdulin/jasmine-examples/src/stackoverflow/54601177/index.test.js:27:17)
    at QueueRunner.attempt (/Users/ldu020/workspace/github.com/mrdulin/jasmine-examples/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:7063:44)
    at QueueRunner.run (/Users/ldu020/workspace/github.com/mrdulin/jasmine-examples/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:7104:25)
    at runNext (/Users/ldu020/workspace/github.com/mrdulin/jasmine-examples/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:7023:18)
    at next (/Users/ldu020/workspace/github.com/mrdulin/jasmine-examples/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:7030:11)
    at QueueRunner.onComplete (/Users/ldu020/workspace/github.com/mrdulin/jasmine-examples/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:6924:9)
    at Immediate._onImmediate (/Users/ldu020/workspace/github.com/mrdulin/jasmine-examples/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:7120:12)
   ✔ should pass too (14ms)
   ✔ should pass (1ms)

>> Done!


Summary:

?  Passed
Suites:  1 of 1
Specs:   2 of 2
Expects: 1 (0 failures)
Finished in 0.024 seconds