Node Test Runner got released with Node v20 as a stable feature. This means we can test our NodeJS applications without installing other 3rd party applications. I have already made an intro on this feature you can read in this article. But to do testing, we need to use some assertion methods. And in this article, I will cover some of them.
Package
To use assertion methods, we need to import them from the appropriate package. Test functions are all located in the node:test package, however, assertion methods are located in the node:assert.
import assert from 'node:assert';
Equality
With this feature, there are multiple functions for testing equality. Some test equality of value, but others test the equality of objects. On top of that, some test strict equality, while others don't. And the difference between those is the same as the difference between double and triple equal.
describe("equality", () => {
it("equal", () => {
assert.equal(1, "1");
});
it("not equal", () => {
assert.notEqual(1, 2);
});
it("strict equal", () => {
assert.strictEqual(1, 1);
});
it("strict not equal", () => {
assert.notStrictEqual(1, "1");
});
it("deep equal", () => {
const result = {a: 1, b: {c: 2}};
const expected = {a: 1, b: {c: 2}};
assert.deepStrictEqual(result, expected);
});
it("not deep equal", () => {
const result = {a: 1, b: {c: 2}};
const expected = {a: 1, b: {c: 3}};
assert.notDeepStrictEqual(result, expected);
});
// deepStrictEqual notDeepStrictEqual
})
Errors
For testing errors, there are two different assertion functions, one testing that it does throw error, and the other that it doesn't.
describe("error", () => {
it("throws error", () => {
function errorThrowingWrapper() {
functionThatThrowsAnError();
}
assert.throws(errorThrowingWrapper);
assert.throws(errorThrowingWrapper, {message: "Custom error message"});
});
it("does not throw error", () => {
function errorThrowingWrapper() {
functionThatDoesNotThrowAnError();
}
assert.doesNotThrow(errorThrowingWrapper);
});
})
Strings matching
Often you can test strings with equality, but sometimes you want to use regex. For that, there is assert.match function.
describe("strings", () => {
it("matching", () => {
const inputString = "test";
const testRegex = /^test$/;
assert.match(inputString, testRegex);
});
})
Promise rejection
In NodeJS it is common to work with async functions. For that, there is the assert.rejects function.
describe("async rejecting", () => {
it("rejects promise", () => {
assert.rejects(
asyncFunctionThatRejects, { error: "Async Reject Error"}
)
});
})
Conclusion
The node test runner is quite a new feature. It has quite a good number of options for testing, however, it is still limited. I hope this list helps with using it, but when using it, do consider current capabilities. You can download the code from my GitHub repository.
For more, you can follow me on Twitter, LinkedIn, GitHub, or Instagram.
Top comments (0)