Print message on expect() assert failure

后端 未结 8 2193
一个人的身影
一个人的身影 2020-12-15 02:11

Is there a way to print a custom error message when a Jasmine expect() fails?

As an example, for end to end testing I have an array of web pages and I u

8条回答
  •  抹茶落季
    2020-12-15 02:59

    The other answers explain how to hack 'expect', but there is another approach that may solve your problem, though it requires you to flip your thinking around a little bit. Instead of thinking of the 'expect' as your behavior under test, think of all the expectations under a single 'it' call as your behavior under test.

    The case where I've come across this problem the most is when I have a function that is doing some kind of intensive parsing and I want to write 20, nearly identical, tests.

    Arrange your inputs and outputs like so:

    var testDatas = [
      {
        input: 'stringtoparse1',
        output: 'String To Parse 1'
      },
      {
        input: 'stringtoparse2',
        output: 'String To Parse 2'
      },
      {
        input: 'stringtoparse3',
        output: 'String To Parse 3'
      },
    ];
    

    Now iterate over the list of your test data, and call 'it' from inside the loop like so:

    testDatas.forEach(function(test) {
      it('should parse for input ' + test.input, function() {
        expect(myParser(test.input).toEqual(test.output);
      });
    });
    

    You get to reduce the amount of extraneous code flying around your tests and you get to format a message for each expectation, or group of expectations.

提交回复
热议问题