0

when I write tests I often use such constructions with assert

 try {
   await asyncFunction(); // expect error
   assert(false) // to make 100% fail
 } catch (err) {
   assert(err) // means 'assert(true) 
 }

Now I need to use "expect" from chai lib and I don't know how to write exactly the same test with 'expect' syntax

  • 2
    Why are you using Chai's expect with Jest? It has its own [expectations](https://jestjs.io/docs/expect) (and [async handling](https://jestjs.io/docs/asynchronous)). Handling promises with _Mocha_ and Chai is well covered at e.g. https://stackoverflow.com/q/26571328/3001761. – jonrsharpe Jun 07 '22 at 08:18

1 Answers1

1

You might try

expect.fail("This should've not happenned");

or another "more readable" alternative

should.fail("This should've not happenned");

Chai docs

In this section looks like there is a cool idiomatic way to perform what you want:

const action = function() { yourSyncFunction() }
expect(action).to.throw(YourError)

And here there's the DSL for testing promises. (You need to install the "As promised" plugin)

yourAsyncFunction().should.be.rejectedWith(Error)
Some random IT boy
  • 7,569
  • 2
  • 21
  • 47
  • 1
    `.to.throw` will not work - `action` _doesn't_ throw an error, it returns a rejected promise. – jonrsharpe Jun 07 '22 at 09:04
  • 1
    You're right. One should check for a rejected promise containing the error! – Some random IT boy Jun 07 '22 at 09:32
  • 1
    And note when handling promises it's critically important that they get settled _during the test_. Unless you return or await the promise, the assertion happens after the test has finished so the test can never fail. – jonrsharpe Jun 07 '22 at 11:44