How to perform an integration test with K6?

Hello,

for an exercise task I should write two integration tests for my PHP website. I have to verifiy whether the returned statuscode and returned content is correct.

Are somewhere examples about this topic available? I can not imagine what I have to do.

I am very grateful for every tip and help!

Hi @hansmueller,

while k6 was primarily built for performance testing, it’s perfectly suited to run integration tests as well.

Your integration tests could:

  • verify the status code of a HTTP response
  • verify the response content (body)
  • do functional testing (authenticate, retrieve objects)
  • check for flaky behavior (run the same test 100 times to see if it’s consistent)
  • check for concurrency issues (run the same test 100 times concurrently)
  • validate API contracts (use the JSON schema to validate the response)
  • many other tests

Take a look at this sample test:

import http from 'k6/http'
import { Counter } from 'k6/metrics'
import { sleep, check as loadTestingCheck } from "k6";

let failedTestCases = new Counter('failedTestCases');

export let options = {
  thresholds: {
    failedTestCases: [{ threshold: 'count==0' }], // add "abortOnFail: true" to stop on the first failure
  },
  iterations: 1, 
  vus: 1,
};

// Functional check (like assert). 
let check = function (obj, conditionArray, tags) {
  let result = loadTestingCheck(obj, conditionArray, tags || {});
  failedTestCases.add(!result);
  return result;
};

export default function () {
  let res = http.get('https://test-api.k6.io/public/crocodiles/'); 

  check(res.status, {
    "API is working": (status) => status === 200
  });

  check(res.json().length, {
    "got 8 crocodiles": (number_of_objects) => number_of_objects === 8
  });

  check(res.json("0.name"), {
    "First crocodile is Bert": (name) => name === "Bert"
  });

  check(res.json("1.name"), {
    "Second crocodile is Pepe": (name) => name === "Pepe"
  });
}

here’s how it looks like when you run k6 run test.js

And here’s how it looks like when you run k6 cloud test.js

If you are looking for inspiration, take a look at the sample script on https://test-api.k6.io/. This test creates a new account, authenticates to the service, retrieves, modifies, and deletes some objects.

We plan to add documentation about integration testing to the official docs by the end of next week. I’ll update this reply once we have documented it.

Let me know if you have any specific questions. Welcome to the community :slight_smile:

2 Likes

Thanks! This is what I was looking for.

Hi @pawel, any update on the documentation ?

Hi Pawel!

Could you explain how this line works ? Why count==0 ?

failedTestCases: [{ threshold: 'count==0' }], // add "abortOnFail: true" to stop on the first failure

For some reason when I add abortOnFail it wont fail, it does not recognize failedTestCases as failures as well, it is not marked in red

Sorry, everything is working correctly.

1 Like