How to write unit tests for an open source contribution
unit vs integration tests, test file location conventions, test naming patterns, arrange-act-assert, mocking dependencies, coverage requirements, test-driven contribution
Tests Are Not Optional
Most projects with active maintenance will reject PRs without tests. Tests prove your fix works and do not regress under future changes. Write the test first -- it clarifies what you are actually trying to fix.
Finding the Right Test File
Look for a tests/ or __tests__/ directory. Find the test file for the module you changed. If one does not exist, create it following the same naming pattern used elsewhere: auth.test.js, test_auth.py.
Writing a Unit Test
// JavaScript (Jest)
describe('AuthService.logout', () => {
it('should not throw when session token is null', () => {
// Arrange
const service = new AuthService({ token: null });
// Act + Assert
expect(() => service.logout()).not.toThrow();
});
it('should clear token on successful logout', () => {
const service = new AuthService({ token: 'abc123' });
service.logout();
expect(service.getToken()).toBeNull();
});
});Coverage
Run coverage locally before pushing: npm test -- --coverage or pytest --cov. Some projects enforce a minimum -- check CI config or CONTRIBUTING.md. If your change drops coverage, add tests. Never skip a test to make coverage numbers look better.
