title: How To "Fake" Date/Time For Testing Mongoose Models
body: <p>Beforehand, thank you for any help/advice you can provide!</p>
  
  <h1>What I'm Trying To Accomplish</h1>
  
  <p>I'm trying to find an elegant way to test the date/time when creating an instance of a Mongoose model.</p>
  
  <p>I'd like to make sure that the time that is stored is the correct time.</p>
  
  <p>My model currently looks like this:</p>
  
  <pre><code>const messageSchema = mongoose.Schema({
    user: { type: String, required: true },
    message: { type: String, required: true },
    created: { type: Date, default: Date.now },
  });
  
  const Message = mongoose.model('Message', messageSchema);
  </code></pre>
  
  <p>I import this model into a mocha test suite, where I'm trying to run a test along the lines of:</p>
  
  <pre><code>const now = {Date message was created}
  it('check time matches time created', () =&gt; {
    expect(message.created).to.equal(now);
  });
  </code></pre>
  
  <h1>What I've Tried So Far</h1>
  
  <p>The way I tried to accomplish this was using <a href="http://sinonjs.org/releases/v4.1.3/fake-timers/" rel="noreferrer">Sinon's Fake timers</a> functionality.</p>
  
  <p>So my test case looks like this:</p>
  
  <pre><code>describe('creating new message', () =&gt; {
    let clock;
    let message;
    let now;
  
    before(() =&gt; {
      clock = sinon.useFakeTimers();
      clock.tick(100);
      message = new Message({
        user: 'Test User',
        message: 'Test Message',
      });
      // Time the message was created
      now = Date.now();
      clock.tick(100);
    });
  
    it('check time matches time created', () =&gt; {
      expect(message.created).to.equal(now);
    });
  });
  </code></pre>
  
  <h1>Why I Assume This Doesn't Work</h1>
  
  <p>I believe that this doesn't work because the <code>Date.now</code> function which is passed as the default for the Mongoose model is isolated from the Sinon fake timer (the fake timer is in the test file, and the model is imported from another file). </p>
  
  <p>Thank you again!</p>