How to Test Classes
Understand the difference between testing classes and testing functions.
We'll cover the following...
In everyday work, we often need to deal with classes (MDN article). Some examples might be one of the following:
- A Node.js API endpoint handler (server side).
- An SPA Component class (client side).
These often include dependencies that are injected in the constructor and used throughout the methods in the class instance.
We’ll look into a class with one dependency and one method that uses that dependency.
The Article
class
What follows is a very simplified example of a class that handles deleting articles in a browser application. It accepts some input and makes a request to a server API if conditions are met.
const specReporter = require('jasmine-spec-reporter').SpecReporter module.exports = { srcDir: "src", srcFiles: [ "**/*.?(m)js" ], specDir: "spec", specFiles: [ "**/*[sS]pec.?(m)js" ], helpers: [ "helpers/**/*.?(m)js" ], random: false, stopSpecOnExpectationFailure: false, browser: { name: "headlessChrome" }, reporters: [new specReporter()] }
Class breakdown
The ArticleDelete
class relies on an ArticleAPI
class to make a DELETE /api/article/:id
call if conditions are met.
-
ArticleAPI
is a class that implements the server API call. It’s empty in the example above because that’s outside of the current lesson scope, and we’ll be mocking its responses for the tests.ArticleDelete ...