API wrapper testing

I am writing an API wrapper for an external API that will be used in our application.

I took a test approach for this project, but since I have little experience writing API wrappers, I’m not sure that I am on the right track.

I understand that I should not test the external API and should not get into the network in my tests. I use Nock to bully my API requests.

However, I'm not sure I'm doing it right.

I made some API requests using curl and put the response (XML) in a file, for example /test/fixtures/authentication/error.js::

module.exports = "<error>Authorization credentials failed.</error>"

Since I don’t want to hit the net, but I want to make sure that my shell parses XML for JSON, I decided that I needed data samples.

My test is as follows:

describe("with an invalid application key", function() {
  var cl, api;
  before(function(done) {
    api = nock(baseApi)
          .get('/v1/auth/authenticate')
          .reply(200, fixtures.authentication.error);
    done();
  });
  after(function(done) {
    nock.cleanAll();
    done();
  });
  it("returns an error", function(done) {
    cl = new APIClient(auth.auth_user, auth.auth_pass, "abcd1234");
    cl.authenticate(function(err, res) {
      should.exist(err);
      err.should.match(/Authorization credentials failed./);
      should.not.exist(res);
      api.isDone().should.be.true;
      done();
    });
  });
});

With my tested code, it looks like this:

APIClient.prototype.authenticate = function(callback) {
  var self = this;
  request({
    uri: this.httpUri + '/auth/authenticate',
    method: 'GET',
    headers: {
      auth_user: this.user,
      auth_pass: this.pass,
      auth_appkey: this.appkey
    }
  }, function(err, res, body) {
    if (err) {
      return callback('Could not connect to the API endpoint.');
    }
    self.parser.parseXML(body, function(err, result) {
      if (err) { return callback(err); }
      if (result.error) { return callback(result.error); }
      self.token = result.auth.token[0];
      return callback(null, result);
    });
  });
};

, , ( "", XML "success", , JSON .

API, , , :

/data/topicdata/realtime/:reportxhours/:topics/:mediatypes/:pageIndex/:pageSize

, (?) URL-. , 30 XML . , , , .. API . ?

- / - API- , , .

+4
1

, , , Zombie .

0

Source: https://habr.com/ru/post/1528051/


All Articles