0

I have this KoaJS application that is serving an API and I am using mocha/supertest to test the API. One of the tests is to make sure that you can create an oauth token through the API. The test looks like this:

it('should be able to create a token for the current user by basic authentication', function(done) {
  request
  .post('/v1/authorizations')
  .auth('active.user', 'password')
  .expect(200)
  .expect({
    status: 'success',
    responseCode: 200,
    data: {
      data: [{
        id: 1,
        type: "access",
        token: "A2345678901234567890123456789012",
        userId: 1,
        note: null,
        oauthApplicationId: 1,
        createdTimestamp: "2014-04-17T23:17:06.000Z",
        updatedTimestamp: null,
        expiredTimestamp: null
      }]
    }
  }, done);
});

The issue here is that token and createdTimestamp are values that I can't determine before the test is executed.

What is the best way to test this situation without mocking the response (because I want this test to actually hit the database and do it needs to do)?

ryanzec
  • 27,284
  • 38
  • 112
  • 169

1 Answers1

5

So superagent's .expect is great and convenient for basic cases with expected values, but don't be afraid to write your own expectation code for more advanced cases such as this.

var before = new Date().valueOf();
request.post('/v1/authorizations')
  //all your existing .expect() calls can remain here
  .end(function(error, res) {
    var createdTimestamp = new Date(res.body.data[0].createdTimestamp).valueOf();
    var delta = createdTimestamp - before;
    assert(delta > 0 && delta < 5000);
    done()
  });

For the token, just assert that it exists, and it a string that matches a regex.

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274