Is this an acceptable way of writing tests?

Since the test body is the same for these situations, I figured I could factor out the things that are different into an array, and run .forEach to run the test on each of them.

describe('Proper output keys', () => {
  const inputs = [
    {
      label: 'should return proper format for unix time input',
      route: '/0',
    },
    {
      label: 'should return proper format for natural date input',
      route: '/January 1, 1970',
    },
    {
      label: 'should return proper format for invalid input',
      route: '/invalid',
      expectedStatusCode: 400
    }
  ];

  const end = (done, code = 200) => (err, res) => {
    res.should.have.status(code);
    res.body.should.be.an('object').that.has.all.keys('unix', 'natural');
    done();
  };

  inputs.forEach(({label, route, expectedStatusCode}) => {
    it(label, (done) => {
      chai.request(server)
        .get(route)
        .end(end(done, expectedStatusCode));
    });
  });
});

Is writing tests like this common?

1 Like

I don’t know how common it is, but I like it.

Sure, do not repeat yourself (DRY).