Blu*_*ame 3 unit-testing node.js jestjs strapi
我正在尝试 Strapi,并希望创建一个通过单元测试验证的控制器。
如何在 Strapi 中设置单元测试?
我写了以下测试
test('checks entity inside boundary',async ()=> {
ctx={};
var result = await controller.findnearby(ctx);
result = {};
expect(result).anyting();
});
Run Code Online (Sandbox Code Playgroud)
但是,在我的控制器中,我有访问全局 Strapi 对象的代码,这会导致此错误ReferenceError: strapi is not defined
strapi.log.info('findNearby');
strapi.log.info(ctx.request.query.lat);
strapi.log.info(ctx.request.query.long);
Run Code Online (Sandbox Code Playgroud)
Strapi 和测试的最佳实践是什么?
小智 6
我通过创建一个助手成功地在 Strapi 中实现了测试
const Strapi = require("strapi");
// above require creates a global named `strapi` that is an instance of Strapi
let instance; // singleton
async function setupStrapi() {
if (!instance) {
await Strapi().load();
instance = strapi;
instance.app
.use(instance.router.routes()) // this code in copied from app/node_modules/strapi/lib/Strapi.js
.use(instance.router.allowedMethods());
}
return instance;
}
module.exports = { setupStrapi };
Run Code Online (Sandbox Code Playgroud)
您可以从现在开始获取所有控制器app.controllers并一一测试它们。
我的 API 端点示例测试(在 Jest 中)如下所示
const request = require("supertest");
const { setupStrapi } = require("./helpers/strapi");
// We're setting timeout because sometimes bootstrap can take 5-7 seconds (big apps)
jest.setTimeout(10000);
let app; // this is instance of the the strapi
beforeAll(async () => {
app = await setupStrapi(); // return singleton so it can be called many times
});
it("should respond with 200 on /heartbeat", (done) => {
request(app.server) // app server is and instance of Class: http.Server
.get("/heartbeat")
.expect(200) // expecting response header code to by 200 success
.expect("Hello World!") // expecting reponse text to be "Hello World!"
.end(done); // let jest know that test is finished
});
Run Code Online (Sandbox Code Playgroud)
我试图在我的博客上介绍这个主题https://medium.com/qunabu-interactive/strapi-jest-testing-with-gitlab-ci-82ffe4c5715a
| 归档时间: |
|
| 查看次数: |
2468 次 |
| 最近记录: |