2

I am writing code that validates texts. This is how I test it. But I don't want to use try--catch in unit testing. Please give me a better way to do it.

it('Testing if hook errors on invalid description.', async () => {
      try {
        workRequest.requestor = 'John';
        workRequest.description = 1;
        result = await app.service('dummy').create(workRequest);
      } catch (error) {
        assert.equal(error.errors.description, 'Description is must be a string');
      }
    });

1 Answer 1

3

what you looking for is somthing like this should.throws almost all tests framework supports this API

for example :

shouldjs

https://shouldjs.github.io/#should-throws

mocha

https://mochajs.org/#bdd

and also

https://nodejs.org/api/assert.html#assert_assert_throws_fn_error_message

 it('Testing if hook errors on invalid description.', async () => {
        assert.throws(  () =>  {
            workRequest.requestor = 'John';
            workRequest.description = 1;
            result = await app.service('dummy').create(workRequest);
        },
  err 
);
Sign up to request clarification or add additional context in comments.

4 Comments

I'm not a JavaScript expert, but I've never seen the syntax of passing in a code block like that, does not have to be () => { ... } instead of { ... }?
you are right thank you @Matthew . i updated my code
How I can know it sends a correct error message? Since I need to validate multi-elements
Just pass to err parameter the expected object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.