Here’s a possibility! Perhaps you are testing your JavaScript with a framework like Jasmine. That’s nice because you can write lots of tests to cover your application, get a nice little UI to see the output, and even integrate it with build and deploy tools to make your ongoing development work safer.
Now, perhaps there is this zany developer on your team who keeps changing API endpoints on you — quite literally breaking things in the process. You decide to write a test that hits those endpoints and makes sure you’re getting back from it what you expect. Straightforward enough. The only slightly tricky part is that API requests are async. To really test it, the test needs to have some way to wait for the results before testing the expectations.
That can be handled in Jasmine through a beforeEach()
, which can wait to complete until you call a done()
function. Here’s the whole thing:
See the Pen
Test Endpoint with Jasmine by Chris Coyier (@chriscoyier)
on CodePen.
Here’s largely the same thing but with Mocha/Chai:
See the Pen
Test Endpoint with Mocha/Chai by Chris Coyier (@chriscoyier)
on CodePen.
This is a great topic to study. It’s so easy to accidentally change an endpoint and can result in a large impact. In the last few years I changed a string status to an object to include a bit more information. We missed the change but the customer was quick to let us know.
I kind of like Frisby as it has support for JSON schema, headers and status code with a straight forward dsl.
https://www.frisbyjs.com/
Jasmine supports promises and async/await as well: https://jasmine.github.io/tutorials/async
Much easier to work with than callback functions. :)
I hate to be “that guy” and I don’t expect you to approve this comment. But I’d argue that is not “two ways”, it is only one way. Even though you’re using two different frameworks, you’re essentially doing the same thing.
I only say this because I was interested to hear what the second method would be, other than the obvious “send a request, check the response”.
Thanks anyway.
Baylor Rae’ beat me to suggesting FrisbyJS, so I’ll politely +1 that suggestion.
I’d avoid testing endpoints client side unless they are 3rd party libraries and are not reliable.
Ideally an API has an SLA in place and if it’s internal, it should have backend tests in place.
Otherwise I’d suggest sticking to Jest for testing.