Don't rely on things that can change without you noticing them
TL;DR: Tests must be in full control.
Using an existing file for testing breaks the golden rule: tests must fully control their environment.
When someone changes the file, the test becomes erratic and unreliable.
That can result in an annoying debugging experience and non-deterministic test runs.
const fs = require('fs');
function trimFile(data) {
return data.trim();
}
// existing_file.txt holds the sample information
// " John Wick "
test('test process file', () => {
const data = fs.readFileSync('existing_file.txt', 'utf8');
expect(trimFile(data)).toBe('John Wick');
});
const fs = require('fs');
const { jest } = require('@jest/globals');
function trimFile(data) {
return data.trim();
}
function generateTestData() {
return ' John Wick ';
}
test('test process file generated', () => {
const data = generateTestData();
expect(trimFile(data)).toBe('John Wick');
});
test('test process file mocked', () => {
jest.spyOn(fs, 'readFileSync').mockReturnValue(' mocked data ');
const data = fs.readFileSync('file.txt', 'utf8');
expect(trimFile(data)).toBe('John Wick');
fs.readFileSync.mockRestore();
});
You can detect this smell by identifying tests that rely on external files instead of generating or mocking the data.
Look for file path references and check if they are necessary.
AI generators might create this smell if they aren't given clear instructions to generate or mock test data instead of using external files.
GPT tools detect this smell if you guide them to check the code for external file dependencies.
Never use existing files and keep your tests runnable to a known state.
You need to generate your test data either by the test or mock it out completely so that tests are in full control.
Code Smell 30 - Mocking Business
Code Smell 254 - Mystery Guest
Code Smell 204 - Tests Depending on Dates
Coupling - The one and only software design problem
Code Smells are my opinion.
Photo by William Warby on Unsplash
Code without tests is broken by design.
Jacob Kaplan-Moss
Software Engineering Great Quotes
This article is part of the CodeSmell Series.