express-validator in your project, install with npm:
Plug in the Middleware
To use the middleware in your code, crack open the part of your app that sets up Express middlewares, and add in a reference to this lil beaut:
1 2 3 4 5 6
Note that you should insert the new
express-validator middleware directly after the
json middleware. Also note that the
json middleware, used in conjunction with
urlencoded now replace
bodyParser to avoid deprecation warnings on startup.
Let’s say you’re writing a validator for new posts to a blog. That code might look like this.
1 2 3 4 5 6
It checks to see if there is a title and a body given. If there is not, the validator will return false, and there will be a validation errors array on the
req object. There are many other assertions (provided internally by validator.js) besides
notEmpty that you can use.
Validating the Validator
First, setup a test helper that stubs the request,
req, for validation:
1 2 3 4 5 6 7 8 9 10 11 12
There’s nothing too incredibly special here. It’s just abstracted out of your test into a reusable helper. The
req object has empty objects to slap fixture data onto in your tests. It includes a stubbed
param function that can return params by name. Finally, the
express-validator middleware is called with the stubbed
Now, in your test, you can simply:
- Stub the request before each test
- Setup your fixture data to make the test pass (or not)
- Assert validation errors’ existence and messages
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
What do you think? Is there an easier way? A way to get better assertions?