Preset for jest testing via MySQL storage
Jest preset for easier setup of MySQL storage.
npm install jest-mysql --save-dev
Or if you use yarn
yarn add jest-mysql --dev
Make sure jest
and mysql
are installed as well in the project, as they are required as peer dependencies.
jest
to use presetIn order for jest
to know about this preset, you needs to configure it.
You could choose one of the following methods, for further reference checkout the jest documentation on configuration and presets
package.json
{
"jest": {
"preset": "jest-mysql",
//any other jest configurations
},
//rest of package.json configuration
}
jest.config.js
into your root directory
module.exports = {
preset: "jest-mysql"
//any other configuration
};
If you have a custom jest.config.js
make sure you remove testEnvironment
property, otherwise it will conflict with the preset.
jest-mysql-config.js
Within the current working directory, create jest-mysql-config.js
.
I.E.
module.exports = {
databaseOptions: {
host: "localhost",
port: 3306,
user: "root",
password: "",
database: "test"
},
createDatabase: true,
dbSchema: "DB_creation.sql",
truncateDatabase: false
};
databaseOptions
- Required {Object} Connection options used to be used by the MySQL clientcreateDatabase
- Optional {Boolean} If this is set to true, a database will be created if database with such name does not exist in your MySQL instancedbSchema
- Optional {String} Path to the MySQL dump schema for the database (this can be any database dump; regardless if data is exported or only the tables structure).truncateDatabase
: Optional {Boolean} If this is set to true, the database will be truncated upon tests finishing, see globalTeardown for further referenceFor utility purposes, the connection to the database has been made available within the global
context
and it can be accessed as follows:
global.db;
If you need further customization after the database has been created and schema imported,
you could provide a custom hooks file which will be exectuted after the initial setup has been completed ( if createDatabase - the database has been created and the connection has been established to the database).
setupHooks.js
async
or Promise
based
const { setupDummyUsers } = require("tests/fixtures/dummyUser");
async function postSetup() {
await setupDummyUsers();
}
module.exports = {
postSetup
};
You should be able to access the connection to the database and query if needed.
Enjoy!
it("should have created a database with User table and 3 dummy user records", done => {
const users = global.db.query(
"SELECT * FROM users",
(error, results, fields) => {
if (error) {
throw error;
}
expect(results).toHaveLength(3);
done();
}
);
});
You can enable debug logs by setting environment variable DEBUG=jest-mysql:*
MIT