Jest server API testing

Hello Team,

I am new to the Javascript and Kibana.
Based on the discussion on Sonarqube topic, i am trying to write a test case for basic hello-world plugin (generated by plugin generator)
I want to achieve something like call the API and test the resposne code or response

created index.js in hello_world/server/__test__ folder

describe('Test API',()=>{
   it('calling API',async()=>{
      await supertest
      .post('/api/hello_world/example')
     .send()
     .expect(200);

   });
});

here is the example.js generated by plugin

export default function (server) {

serevr.route({
    path: 'api/hello_world/example',
    method: 'GET',
    handler () {
        return { time : (new Date()).toISOString() };
    }

});

}

Few queries here,

  1. how to get supertest in this file.
  2. is Kibana and elasticsearch expected to run in background
  3. How can i execute this single test.

Could you please help me with the pointers to achieve this API testing.
Thank you for your help and support!

You should be able to import it directly as it's already a dependency of Kibana.

Yes, but we have some utilities to help with this using our integration test framework, which is mentioned in our docs here.

Here's an example jest integration test which might be a helpful reference: https://github.com/elastic/kibana/blob/master/src/plugins/security_oss/server/routes/integration_tests/anonymous_access_capabilities.test.ts

Another option is writing your own functional test (not in jest), which is explained here.

Functional test example: https://github.com/elastic/kibana/blob/master/test/api_integration/apis/status/status.js

Overall the integration tests are more lightweight, so if you just want to test your API and don't have extensive needs for a bunch of sample test data in Elasticsearch, I'd go with that option. Only use functional tests if you know you need them.

To run a jest integration test: yarn test:jest_integration plugins/my-plugin/server/integration_tests/my_test_file.ts

To run an API functional test: node scripts/functional_tests_server --config [directory]/config.js node, and then once the server fires up: scripts/functional_test_runner --config [directory]/config.js

More on that in our docs as well.

Hope this helps a bit! :slightly_smiling_face:

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.