Skip to content

Instantly share code, notes, and snippets.

@alcir-junior-caju
Last active February 1, 2023 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alcir-junior-caju/89dbca11576e99ab8556d67134ba6067 to your computer and use it in GitHub Desktop.
Save alcir-junior-caju/89dbca11576e99ab8556d67134ba6067 to your computer and use it in GitHub Desktop.
Setup Tests Strapi with Typescript
import request from 'supertest';
import { describe, beforeAll, afterAll, it, expect } from '@jest/globals';
import { setupStrapi, stopStrapi } from '../config/strapi';
import {
account,
createPermissions,
createRoles,
createUser
} from '../factories';
let user;
let jwt;
const typeRole = 'technician';
/** this code is called once before any test is called */
beforeAll(async () => {
await setupStrapi(); // singleton so it can be called many times
const { permissions } = await createPermissions('account');
await createRoles({ typeRole, permissions });
user = await createUser({ typeRole });
jwt = strapi.plugins['users-permissions'].services.jwt.issue({
id: user.id
});
}, 1000000);
/** this code is called once before all the tested are finished */
afterAll(async () => {
await stopStrapi();
}, 1000000);
describe('Account API', () => {
describe('POST', () => {
it('should be create Account data for technician user', async () => {
await request(strapi.server.httpServer)
.post('/api/accounts')
.set('accept', 'application/json')
.set('Content-Type', 'application/json')
.set('Authorization', 'Bearer ' + jwt)
.send({ data: account })
.expect('Content-Type', /json/)
.expect(200);
});
});
});
import { describe, beforeAll, afterAll, it, expect } from '@jest/globals';
import { setupStrapi, stopStrapi } from '../config';
beforeAll(async () => {
await setupStrapi(); // singleton so it can be called many times
}, 1000000);
afterAll(async () => {
await stopStrapi();
}, 1000000);
describe('Strapi', () => {
it('should define the strapi', () => {
// const
expect(strapi).toBeDefined();
});
});
const config = require('./jest.config');
module.exports = {
...config,
testMatch: ['<rootDir>/tests/**/?(*.integration.)+(spec|test).[jt]s?(x)']
};
const config = require('./jest.config');
module.exports = {
...config,
testMatch: ['<rootDir>/tests/**/?(*.unit.)+(spec|test).[jt]s?(x)']
};
module.exports = {
collectCoverageFrom: [
'config/**/*.{js,jsx,ts,tsx}',
'src/**/*.{js,jsx,ts,tsx}',
'src/api/**/controllers/*.{js,jsx,ts,tsx}',
'src/api/**/routes/*.{js,jsx,ts,tsx}',
'src/api/**/services/*.{js,jsx,ts,tsx}',
'src/api/**/utils/*.{js,jsx,ts,tsx}'
],
globals: {
__PATH_PREFIX__: ``
},
moduleDirectories: ['node_modules', 'src'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
preset: 'ts-jest',
testPathIgnorePatterns: [
'<rootDir>/__mocks__/*',
'node_modules',
'\\.tmp',
'\\.cache',
'<rootDir>.*/public',
'<rootDir>/dist/*'
],
transform: {
'^.+\\.[tj]sx?$': [
'ts-jest',
{
tsconfig: 'tsconfig.test.json'
}
]
},
roots: ['<rootDir>/tests/', '<rootDir>/config/', '<rootDir>/src/'],
testEnvironment: 'node'
};
{
...
"scripts": {
...,
"test": "jest --runInBand --forceExit --detectOpenHandles --passWithNoTests",
"test:unit": "jest --runInBand --forceExit --detectOpenHandles --config=jest-unit.config.js --passWithNoTests",
"test:integration": "jest --runInBand --forceExit --detectOpenHandles --config=jest-integration.config.js --passWithNoTests",
"test:coverage": "jest --runInBand --forceExit --detectOpenHandles --coverage"
},
"devDependencies": {
...,
"jest": "^29.4.1",
"ts-jest": "^29.0.5",
"sqlite3": "^5.1.4",
"supertest": "^6.3.3"
},
...
}
const defaultPermissions = [
{ action: 'api::account.account.create' },
{ action: 'api::account.account.update' },
{ action: 'api::account.account.find' },
{ action: 'api::account.account.findOne' },
{ action: 'api::account.account.delete' },
{ action: 'api::account.account.patch' },
{ action: 'api::account.account.import' }
];
export const createPermissions = async (typeCollection: string) => {
await strapi.query('plugin::users-permissions.permission').createMany({
data: defaultPermissions
});
const permissions = await strapi
.query('plugin::users-permissions.permission')
.findMany({
where: {
action: {
$contains: typeCollection
}
}
});
return { permissions };
};
type Permission = {
id: number;
action: string;
createdAt: string;
updatedAt: string;
};
type CreateRoleParams = {
typeRole: string;
permissions: Permission[];
};
const defaultRoles = {
technician: {
name: 'Technician',
type: 'technician',
description: 'Default role given to admin user.'
}
};
export const createRoles = async ({
typeRole = 'technician',
permissions
}: CreateRoleParams) => {
await strapi.query('plugin::users-permissions.role').create({
data: {
...defaultRoles[typeRole],
permissions
}
});
};
{
"extends": "@strapi/typescript-utils/tsconfigs/server",
"compilerOptions": {
"rootDir": ".",
"allowJs": true
},
"include": ["./", "src/**/*.json"],
"exclude": [
"node_modules/",
"build/",
"dist/",
".cache/",
".tmp/",
"src/plugins/**"
]
}
type User = {
password?: string;
provider?: string;
confirmed?: boolean;
};
type CreateUserParams = {
data?: User;
typeRole?: string;
};
/**
* Default data that factory use
*/
export const defaultData = {
password: '1234Abc',
provider: 'local',
confirmed: true
};
/**
* Returns random username object for user creation
* @param {object} options that overwrites default options
* @returns {object} object that is used with `strapi.plugins["users-permissions"].services.user.add`
*/
export const mockUserData = (options = {}) => {
const usernameSuffix = Math.round(Math.random() * 10000).toString();
return {
username: `tester${usernameSuffix}`,
email: `tester${usernameSuffix}@strapi.com`,
...defaultData,
...options
};
};
/**
* Creates new user in strapi database
* @param data
* @returns {object} object of new created user, fetched from database
*/
export const createUser = async ({ data, typeRole }: CreateUserParams) => {
/** Gets the default user role */
const pluginStore = await strapi.store({
type: 'plugin',
name: 'users-permissions'
});
const settings = await pluginStore.get({
key: 'advanced'
});
const role = await strapi
.query('plugin::users-permissions.role')
.findOne({ where: { type: typeRole || settings.default_role } });
/** Creates a new user and push to database */
return strapi
.plugin('users-permissions')
.service('user')
.add({
...mockUserData(),
...data,
role: role ? role.id : null
});
};
export default {
mockUserData,
createUser,
defaultData
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment