【问题标题】:Write unit testing for Strapi APIs为 Strapi API 编写单元测试
【发布时间】:2020-04-08 13:38:18
【问题描述】:

我正在尝试开始为 Strapi 端点或 API 编写单元测试。因为它与 Express 完全不同,并且在我看来没有 app.route 概念。我不确定如何开始。

我曾使用 Mocha、Sinon 和 Chai 为 API 编写单元测试套件。但是他们如何使用 Strapi API 是我的问题。

如果有人对 Strapi API 进行单元测试,这对我来说将是一个很好的开端。

用被测代码更新问题

控制器/checkStatus.js

module.exports = {

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

服务/checkstatus.js

module.exports = {

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

【问题讨论】:

  • 请提供被测代码。需要更多细节和重点
  • @slideshowp2:这是我要测试的代码。我已经更新了上面的问题。请检查并让我知道您是否可以帮助我。

标签: node.js unit-testing mocha.js sinon strapi


【解决方案1】:

正如Chai-http 文档所说的那样简单:

您也可以使用基本网址作为请求的基础。

在上述链接页面中查找 URL 部分。

非常基本的测试代码,包含测试您的 API 的 Strapi 开发版本所需的所有样板,如下所示:

// 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();
            });;
    });

});

这更像是一种集成而不是单元测试,但它已经涵盖了您的 Strapi 测试需求。

如果您想要用于 Mocha/Chai-http 测试的 async/await 版本,请参考this SO answer

【讨论】:

    猜你喜欢
    • 2020-11-03
    • 2011-11-14
    • 2014-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    相关资源
    最近更新 更多