cancel
Showing results for 
Search instead for 
Did you mean: 

CAP: Mocking requests to third party Services in tests

muellinho
Explorer

Hello experts,

in my CAP project I'm sending OData Requests to an external API to fetch some data and work on that data.

I wanted to write a Test to make sure, that the operations I do on the data that the external API returns, return the result that I expect.

I'm running my tests via the following command

npx jest --collectCoverage

And in my test start a CDS Server using the following statements:

const project = __dirname+'/..'; // The projects root folder
const cds = require('@sap/cds/lib');
cds.test(project);

as recommended in the documentation capire - Testing (cloud.sap).

When my module which makes a request to the external API is called, and tries to cds.connect.to('service-name') the Service that I'm using, I'm receiving the error message:

"Error: No credentials configured for <service-name>".

I guess that this is actually fine though, since in my CDS config I only provided the credentials for the production profile, to enable local testing through sqlite / mockdata provided via corresponding csv-files:

...
"service-name": {
    "kind": "odata-v2",
    "model": "path/to/srv/model",
    "[production]":{
        "credentials": {
            "destination": "myDestination"
        }
    }
}

Now my question is:

Can I make 'cds.test(...)' run the CAP server using my mockdata from the directory "srv/external/data" the same way as 'cds watch' does or is there another way to mock external APIs when executing tests?

Unfortunately I didn't find anything regarding this topic.

Thanks for any help / hints,

Regards

Jan

View Entire Topic
muellinho
Explorer

Hi,

I found the following solution for my problem, so I'm sharing it before closing the question:

CDS.test() can take more than 1 argument. The additional arguments are then passed to the cds serve command under the hood, so executing

cds.test(project,'--with-mocks');

instead of

cds.test(project);

started the CAP server in my Jest tests with the mockdata of my CSV files and then also didn't try to connect to the remote services.

Best regards

Jan