This error occurs when a test assertion fails using Node.js assert.strictEqual(), indicating that the actual value does not match the expected value using strict equality (===).
The AssertionError is thrown by Node.js's built-in assert module when an assertion test fails. When using assert.strictEqual(), this error indicates that two values are not strictly equal according to the === operator. Unlike assert.equal() which uses loose equality (==), assert.strictEqual() performs strict equality checking, meaning both the value AND type must match. This makes it more precise for testing and helps catch subtle bugs where values appear equal but have different types. The error object includes helpful debugging properties: err.actual (the actual value received), err.expected (the expected value), err.operator ("strictEqual"), and err.code ("ERR_ASSERTION"). These properties help you quickly identify what went wrong in your test.
Read the AssertionError message carefully. It shows both the actual and expected values:
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected
+ 'hello'
- 'Hello'The + line shows what you got (actual), and the - line shows what you expected. Look for differences in:
- Value content
- Data types
- Whitespace
- Case sensitivity
Use typeof or console.log to check the types of both values:
const actual = functionUnderTest();
const expected = 42;
console.log('Actual:', actual, typeof actual); // "42" string
console.log('Expected:', expected, typeof expected); // 42 number
// This will fail:
assert.strictEqual(actual, expected);
// Fix: Convert to same type
assert.strictEqual(Number(actual), expected);
// OR
assert.strictEqual(actual, String(expected));Common type mismatches include number vs string, null vs undefined, and boolean vs truthy values.
For comparing objects or arrays, use assert.deepStrictEqual() instead:
// This FAILS with strictEqual (compares references):
const actual = [1, 2, 3];
const expected = [1, 2, 3];
assert.strictEqual(actual, expected); // AssertionError
// This PASSES with deepStrictEqual (compares content):
assert.deepStrictEqual(actual, expected); // ✓
// Also works for objects:
const user = { name: 'Alice', age: 30 };
const expectedUser = { name: 'Alice', age: 30 };
assert.deepStrictEqual(user, expectedUser); // ✓Use strictEqual only for primitives (strings, numbers, booleans) and reference equality checks.
If the assertion correctly identifies a mismatch, fix your code or update the test:
// Example: Function returns wrong value
function calculateTotal(items) {
return items.reduce((sum, item) => sum + item.price, 0);
}
// Test fails because function doesn't handle empty arrays
const result = calculateTotal([]);
assert.strictEqual(result, 0); // Passes
// But if function had a bug:
function calculateTotalBuggy(items) {
return items.reduce((sum, item) => sum + item.price); // No initial value!
}
const buggyResult = calculateTotalBuggy([]);
assert.strictEqual(buggyResult, 0); // FAILS - returns undefined
// Fix: Add initial value or handle empty caseSometimes the test expectation is wrong and needs updating after legitimate code changes.
Ensure async operations complete before assertions run:
// WRONG: Assertion runs before async operation completes
function testAsync() {
let result;
fetchData().then(data => result = data);
assert.strictEqual(result, 'expected'); // FAILS - result is undefined
}
// CORRECT: Use async/await
async function testAsyncCorrect() {
const result = await fetchData();
assert.strictEqual(result, 'expected'); // Waits for data
}
// OR: Use callbacks/promises properly
function testAsyncCallback(done) {
fetchData().then(data => {
assert.strictEqual(data, 'expected');
done();
});
}Most test frameworks (Jest, Mocha) support async tests natively.
Floating Point Comparisons
When comparing floating point numbers, use a tolerance-based approach instead of strict equality:
function assertAlmostEqual(actual, expected, tolerance = 1e-10) {
assert.ok(Math.abs(actual - expected) < tolerance,
`Expected ${actual} to be close to ${expected}`);
}
assertAlmostEqual(0.1 + 0.2, 0.3); // Handles floating point precisionCustom Error Messages
Provide descriptive custom messages to make failures easier to debug:
assert.strictEqual(
user.status,
'active',
`User ${user.id} should be active but is ${user.status}`
);Strict Mode vs Legacy Mode
Always use strict assertion methods (strictEqual, deepStrictEqual, throws, etc.) instead of legacy methods (equal, deepEqual). Strict mode is recommended by Node.js and provides:
- More accurate comparisons
- Better error messages with visual diffs
- Consistency with modern JavaScript practices
Object.is() Semantics
assert.strictEqual() uses Object.is() internally, which treats NaN === NaN as true and +0 === -0 as false, differing slightly from ===:
assert.strictEqual(NaN, NaN); // Passes (Object.is)
assert.strictEqual(+0, -0); // Fails (Object.is distinguishes)
assert.strictEqual(0 === -0); // true (regular ===)Error: Listener already called (once event already fired)
EventEmitter listener already called with once()
Error: EACCES: permission denied, open '/root/file.txt'
EACCES: permission denied
Error: Invalid encoding specified (stream encoding not supported)
How to fix Invalid encoding error in Node.js readable streams
Error: EINVAL: invalid argument, open
EINVAL: invalid argument, open
TypeError: readableLength must be a positive integer (stream config)
TypeError: readableLength must be a positive integer in Node.js streams