I’ve been setting up testing with a postgres database ( I would use sqlite, however Windows has issues with this as mentioned in the docs ). I’m using Jest, and have followed the instructions in the docs.
Everything is working well, however I don’t know how to ‘clear’ the database after the tests have run. I’m not a database expert, so would appreciate being pointed in the right direction. Something like drop all tables would be sufficient I think.
I have this in my Jest app.test.js file:
afterAll(async (done) => {
// I'm assuming that Knex would be used
const knex = strapi.connections.default;
//delete test database after all tests
knex.raw( ' some sort of empty database query ' )
done();
});
I appreciate any help that you can provide. Thanks.
const Strapi = require('strapi');
const http = require('http');
let instance;
async function setupStrapi() {
if (!instance) {
/** the following code in copied from `./node_modules/strapi/lib/Strapi.js` */
await Strapi().load();
instance = strapi; // strapi is global now
await instance.app
.use(instance.router.routes()) // populate KOA routes
.use(instance.router.allowedMethods()); // populate KOA methods
instance.server = http.createServer(instance.app.callback());
}
return instance;
}
./tests/app.spec.js
const { setupStrapi, closeDatabase } = require('./helpers'); // you might also add jest.setTimeout(newTimeout) if needed in this file.
// 1. unit under test
describe('Global Strapi', () => {
/** this code is called once before any test is called */
beforeAll(async () => {
await setupStrapi(); // singleton so it can be called many times
});
/** this code is called once before all the tested are finished */
afterAll(async () => {
await closeDatabase();
});
// 2. scenario and 3. expectation
test('When setting up properly strapi should be defined', () => {
expect(strapi).toBeDefined();
});
});
This allows you to use sqlite for jest testing with windows. Problem was, strapi does not close the connections by default, so you have to close the strapi db connection before you unlink the .tmp/test.db file.