1

I am testing CRUD API-Operations (https://api.sap.com/api/OP_API_MAINTNOTIFICATION/overview?ReleaseInfo=2021%20FPS02), with mochajs and chai.


let chai = require("chai");
let chaiHttp = require("chai-http");

//Assertion Style
chai.should();
chai.use(chaiHttp);

describe("API TEST", function () {
    it.only('Get all notifications', function (done) {
        const url = "https://sandbox.api.sap.com/s4hanacloud/sap/opu/odata/sap/API_MAINTNOTIFICATION/MaintenanceNotification";
        /**/
        chai.request(url)
            .post('/auth/sign_in')
            // send user login details
            .send({
                'user': 'ExampleEmail',
                'password': 'ExamplePassword'
            })
            .end(function (err, res) {
                var token = res.body.token;
                console.log(token);
                done();
            });

       chai.request(url)
        .get('')
        .set("Authorization", "Bearer " + token)
        .end(function (err, res) {
            done();
        });
    });
});

Issue

In order to test the GET function it is required for the user to authorize oneself

{"fault":{"faultstring":"Failed to resolve API Key variable request.header.apikey","detail":{"errorcode":"steps.oauth.v2.FailedToResolveAPIKey"}}}
  • I did the authorization in this manner / gotten the token but it doesn't work yet(the token is empty), as well as the path "/auth/sign_in" seemingly isn't working

Questions

  • How to do the Authorization for an API in mochajs in order to test said API ?
Roman
  • 43
  • 8
  • It's going to depend on the API. But right off the bat: how do you think your test can be `done()` _twice_? Why not use promises? – jonrsharpe Nov 14 '22 at 19:45
  • quite new to `mochaJS`, this particular implementation that i found was done in this manner. @jonrsharpe, what should there be instead ? – Roman Nov 14 '22 at 19:53
  • Hi there! I have a completely different question for you. Why do you need to test that API? For what I'm seeing that looks like an integration test (mostly because you are calling an external URL, so you won't be able to mock anything) and if that's the case, you'd probably need to follow the whole authentication flow before calling that endpoint – Facundo Gallardo Nov 14 '22 at 22:40
  • @FacundoGallardo, there is a different `URL` that uses said `API`, which via `Postman` can be tested (`GET`, `POST`, `PUT`). I wanted to replicate the `Postman` request with `mocha`, for obvious reasons of creating tests for it. The different `URL` is for my job, hence i cant share it here. – Roman Nov 15 '22 at 08:56

1 Answers1

0

The answer to the question has been found. Send the following authorization with any CRUD Operation:

.auth('Username', 'Password')

Credit: Setting Basic Auth in Mocha and SuperTest @yves-m

Roman
  • 43
  • 8