Snapshot Testing Constants
Adding just few lines of code to prevent silly mistakes.
I have the habit of defining my global configuration constant values in NodeJS projects by creating a constants directory consisting of multiple files, each of which exports a single constant. The directory structure could look like this:
|- constants/ |- Region.ts |- AccountId.ts |- AccountDomain.ts |- index.ts # re-exports all constants from above filesThe structure, naming conventions, re-exporting or not, or other specifics don't matter: This is just an example how I like to do it. You could have just a single file with all the constants, but my brain can't hold that much information at once, so I like to split things into smaller chunks.
These constants are global configuration values that usually have a huge impact on how the application behaves – or doesn't! For example, changing AWS Region values could lead to catastrophic problems. As they are constant values, you shouldn't be changing them that much; But sometimes you do, either on purpose – or by accident. I'm always scared of myself and want to prevent accidents.
I use Vitest for testing (but this'll work fine with Jest as well): I create a single test file constants/index.test.ts, where I import all the constants and perform a snapshot test on them:
import * as constants from ".";test("match snapshot", () => { expect(constants).toMatchSnapshot(); // 👈 where the magic happens});This way, I don't have to worry about making silly mistakes with my global configuration constants as the snapshot test will fail if I do. But if I do modify them on purpose, I just need to accept the snapshot diff by running vitest --update.