1

I'm writing some expect.js matchers and I'd like to test the matchers themselves. So I want to write positive and negative tests. Let's say I've written

toContainItem(name);

used like this;

expect(femaleNames).toContainItem('Brad'); // test fails
expect(femaleNames).toContainItem('Angelina'); // test passes

What I want to do is write a test for the negative case, like so;

 it('should fail if the item is not in the list', function() {
     expect(function() {
         expect(femaleNames).toContainItem('Brad'); 
     }).toFailTest('Could not find "Brad" in the array');
 });

I'm not sure how to run my failing test code in an environment where it doesn't fail the containing test. Is this possible?


EDIT: Based on Carl Manaster's answer, I've come up with an extension to expect, allowing the code above to work;

expect.extend({
    toFailTest(msg) {
        let failed = false;
        let actualMessage = "";
        try
        {
            this.actual();
        } 
        catch(ex)
        {
            actualMessage = ex.message;
            failed = true;
        }

        expect.assert(failed, 'function should have failed exception');

        if(msg) {
            expect.assert(actualMessage === msg, `failed test: expected "${msg}" but was "${actualMessage}"`);
        }
    }
});
Carl Manaster
  • 39,912
  • 17
  • 102
  • 155
Steve Cooper
  • 20,542
  • 15
  • 71
  • 88

1 Answers1

1

I would think you could wrap the inner expect in a try/catch block, where you clear a failure variable in the catch clause, then make your actual assertion about the value of the variable.

let failed = true;
try {
  expect(femaleNames).toContainItem('Brad');
} catch (e) {
  failed = false;
}
expected(failed).toBe(false);
Carl Manaster
  • 39,912
  • 17
  • 102
  • 155
  • 1
    Thanks Carl -- will give it a go! Didn't know that it worked through exceptions. – Steve Cooper Jan 01 '17 at 21:21
  • 1
    Carl - thanks for this. It's the core of the solution I came up with, now edited back into my question. All I've done is wrap it up so that you can write `expect(fn).toFailTest(expectedErrorMessage)` – Steve Cooper Jan 01 '17 at 22:48