Tuesday 16 May 2017

Testing a fire and forget update

My end goal is to be able to limit requests to my express endpoint by reading and saving when a user last hit the endpoint. In the event of database failures, I would not care if this functionality stopped working so as not to disrupt my users.

I update a mongoose model after res.render(...) with the time. I want to be able to do this after completing the response (so the user is not affected by my database operation) and care about errors from the update operation for logging purposes only. I am having trouble testing this and do not know why. Am I preventing the update from executing? Here is a simplified test case that demonstrates the problem and here is what I think is happening in my test:

  1. User is created.
  2. Update started. No then() handler set.
  3. Set timeout for some reasonable time. I figured that 1500ms is more than enough to let the update happen from the previous step.
  4. setTimeout fires so the user is found and asserted on.

I expected the user to be updated but it is not.

const chai = require('chai');
const server = require('../app');
const should = chai.should();
const User = require('../models/User');

afterEach(() => {
  return User.remove({});
});

describe('Fire and forget update', () => {
  it('should work', (done) => {
    User.create({ profileId: 10 })
    .then((originalDoc) => {
      User.update({ profileId: 10 }, { newThing: true }).exec();
      setTimeout(() => {
        User.findOne({ profileId: 10 })
        .exec()
        .then((updatedDoc) => {
          updatedDoc.should.have.property('newThing');
          done();
        });
      }, 1500);
    });
  });
});



via Chip Thien

No comments:

Post a Comment