简体   繁体   中英

Write unit testing for Strapi APIs

Am trying to start writing Unit test for Strapi endpoint or APIs. Since it is way different from Express and does not have a app.route concept in my view. I am not sure on how to start with.

I have had experience in write unit test suits for APIs with Mocha, Sinon and Chai. But how do they work with Strapi APIs is my question.

If anyone having knowledge on unit testing Strapi API, it will be a great head start for me.

Updating the question with code under test

controllers/checkStatus.js

module.exports = {

    checkStatus: async (ctx) => {
       return strapi.services.checkstatus.getStatus(ctx.request.body.id);
    }
};

services/checkstatus.js

module.exports = {

    getStatus: (id) => {
       return id;
    }
};

As Chai-http documentation says it is as easy as this:

You may also use a base url as the foundation of your request.

Look up the URL section in the above linked page.

The very basic test code with all required boiledplate for testing Strapi development version of your API could be as follows:

// Somewhere in your straiproject/tests/YourStrapiAPITest.spec.js

'use strict';

import 'chai-http';
import * as chai from 'chai';

const chaiHttp = require('chai-http');
const assert = chai.assert;

chai.use(chaiHttp);

describe('YourStrapiAPITest', function(done) {

    it('Should return 200 with expected JSON', function() {
        // Ensure your porject is up and running
        // with `npm run develop` or `npm run start`
        chai.request('http://localhost:1337/yourcustomcontenttype')
            .get('/')
            .send()
            .end(function(err, res) {
                assert.equal(res.status, 200);
                // More assertions to test the actual
                // response data vs the expected one.
                done();
            });;
    });

});

This is more of an integration than unit testing but it has got your Strapi test demands covered.

If you want an async/await version for Mocha/Chai-http testing please refer to this SO answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM