Avoid global test fixtures and seeds, add data per-test

One Paragraph Explainer

Going by the golden testing rule - keep test cases dead-simple, each test should add and act on its own set of DB rows to prevent coupling and easily reason about the test flow. In reality, this is often violated by testers who seed the DB with data before running the tests (also known as ‘test fixture’) for the sake of performance improvement. While performance is indeed a valid concern — it can be mitigated (e.g. In-memory DB, see “Component testing” bullet), however, test complexity is a much painful sorrow that should govern other considerations. Practically, make each test case explicitly add the DB records it needs and act only on those records. If performance becomes a critical concern — a balanced compromise might come in the form of seeding the only suite of tests that are not mutating data (e.g. queries)

Code example: each test acts on its own set of data

  1. it('When updating site name, get successful confirmation', async () => {
  2. //test is adding a fresh new records and acting on the records only
  3. const siteUnderTest = await SiteService.addSite({
  4. name: 'siteForUpdateTest'
  5. });
  6. const updateNameResult = await SiteService.changeName(siteUnderTest, 'newName');
  7. expect(updateNameResult).to.be(true);
  8. });

Code Example – Anti Pattern: tests are not independent and assume the existence of some pre-configured data

  1. before(() => {
  2. //adding sites and admins data to our DB. Where is the data? outside. At some external json or migration framework
  3. await DB.AddSeedDataFromJson('seed.json');
  4. });
  5. it('When updating site name, get successful confirmation', async () => {
  6. //I know that site name 'portal' exists - I saw it in the seed files
  7. const siteToUpdate = await SiteService.getSiteByName('Portal');
  8. const updateNameResult = await SiteService.changeName(siteToUpdate, 'newName');
  9. expect(updateNameResult).to.be(true);
  10. });
  11. it('When querying by site name, get the right site', async () => {
  12. //I know that site name 'portal' exists - I saw it in the seed files
  13. const siteToCheck = await SiteService.getSiteByName('Portal');
  14. expect(siteToCheck.name).to.be.equal('Portal'); //Failure! The previous test change the name :[
  15. });