lundi 14 novembre 2016

How to deal with setInterval in server tests

Lets say we are using setInterval inside of a hapi plugin, like so:

// index.js

internals = {
  storage: {},
  problemFunc: () => {
    setInterval((storage) => {
      storage.forEach((problem) => {
        problem.foo = 'bar';
      });
    }, 500);
  }
};

module.exports.register = (server, options, next) => {
  server.on('start', () => { // called when the server starts
    internals.storage.problem1 = {};
    internals.storage.problem2 = {};
    internals.storage.problem3 = {};
    internals.problemFunc(internals.storage);
  });
}

In our tests for this server, we may start up and stop the server many times to test different aspects of the server. Sometimes, we will get an error like cannot set property 'foo' of undefined. This is because the server gets shutdown right before that async code runs, and internals.storage.problem gets removed right along with the server stop.

This makes total sense, and I don't have a problem with that. I'd really like to know what would be some good ways to make sure my tests work 100% of the time rather than 90% of the time.

We could do:

problemFunc: () => {
  setInterval((storage) => {
    storage.forEach((problem) => {
      if (problem !== undefined) {  // check if deleted
        problem.foo = 'bar';
      }
    });
  }, 500);
}

or:

problemFunc: () => {
  setInterval((storage = {}) => {  // default assignment
    storage.forEach((problem) => {
        problem.foo = 'bar';
    });
  }, 500);
}

But I would rather not add conditionals to my code just so that my tests pass. Also, this can cause issues with keeping 100% code coverage because then sometimes that conditional will get run and sometimes it wont. What would be a better way to go about this?

Aucun commentaire:

Enregistrer un commentaire