96 lines
2.3 KiB
JavaScript
Raw Normal View History

'use strict';
2021-01-05 14:24:53 +01:00
const { get } = require('lodash/fp');
const _ = require('lodash');
const modelsUtils = require('../models');
2021-04-29 13:51:12 +02:00
const { sanitizeEntity } = require('../../../packages/core/utils');
2021-01-04 11:32:43 +01:00
const actionRegistry = require('./action-registry');
2021-01-05 14:24:53 +01:00
const { createContext } = require('./context');
const createTestBuilder = (options = {}) => {
const { initialState } = options;
2021-01-05 14:24:53 +01:00
const ctx = createContext(initialState);
return {
get models() {
2021-01-05 14:24:53 +01:00
return ctx.state.models;
},
get fixtures() {
2021-01-05 14:24:53 +01:00
return ctx.state.fixtures;
},
sanitizedFixtures(strapi) {
return _.mapValues(this.fixtures, (value, key) => this.sanitizedFixturesFor(key, strapi));
},
sanitizedFixturesFor(modelName, strapi) {
2021-07-05 18:35:16 +02:00
const model = strapi.getModel(`application::${modelName}.${modelName}`);
const fixtures = this.fixturesFor(modelName);
return sanitizeEntity(fixtures, { model });
},
fixturesFor(modelName) {
return this.fixtures[modelName];
},
2021-01-05 14:24:53 +01:00
addAction(code, ...params) {
const actionCreator = get(code, actionRegistry);
ctx.addAction(actionCreator(...params));
return this;
},
2021-01-05 14:24:53 +01:00
addContentType(contentType) {
return this.addAction('contentType.create', contentType);
},
addContentTypes(contentTypes, { batch = true } = {}) {
2021-01-05 14:24:53 +01:00
return this.addAction(
batch ? 'contentType.createBatch' : 'contentType.createMany',
contentTypes
);
},
addComponent(component) {
2021-01-05 14:24:53 +01:00
return this.addAction('component.create', component);
},
2021-01-04 11:32:43 +01:00
addFixtures(model, entries) {
2021-01-05 14:24:53 +01:00
return this.addAction('fixtures.create', model, entries, () => this.fixtures);
},
async build() {
2021-01-05 14:24:53 +01:00
for (const action of ctx.state.actions) {
await action.build(ctx);
}
2021-01-05 14:24:53 +01:00
return this;
},
2021-01-04 11:32:43 +01:00
async cleanup(options = {}) {
const { enableTestDataAutoCleanup = true } = options;
2021-01-05 14:24:53 +01:00
const { models, actions } = ctx.state;
2021-01-04 11:32:43 +01:00
if (enableTestDataAutoCleanup) {
2021-01-05 14:24:53 +01:00
for (const model of models.reverse()) {
2021-07-05 18:35:16 +02:00
await modelsUtils.cleanupModel(model.modelName);
2021-01-04 11:32:43 +01:00
}
}
2021-01-05 14:24:53 +01:00
for (const action of actions.reverse()) {
await action.cleanup(ctx);
}
2021-01-05 14:24:53 +01:00
ctx.resetState();
return this;
},
};
};
2021-01-04 11:32:43 +01:00
module.exports = { createTestBuilder };