Strapi Unit Testing - strapi is not defined

System Information
  • Strapi Version: 3.6.2
  • Operating System: Ubuntu 18.04.5 LTS
  • Database: sqlite3
  • Node Version: 12.22.1
  • NPM Version: 6.14.12
  • Yarn Version: 1.22.5

Hello,

I am trying to setup my strapi tests according to Unit Testing - Strapi Developer Documentation. However, I am getting the following errors:

Here is my ./config/env/test/database.json file and my ./tests/helpers/strapi.js file:

{
  "defaultConnection": "default",
  "connections": {
    "default": {
      "connector": "bookshelf",
      "settings": {
        "client": "sqlite",
        "filename": ".tmp/test.db"
      },
      "options": {
        "useNullAsDefault": true,
        "pool": {
          "min": 0,
          "max": 1
        }
      }
    }
  }
}
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;
}
module.exports = { setupStrapi };

Here is my ./tests/app.test.js file:

const fs = require('fs');
const { setupStrapi } = require('./helpers/strapi');

jest.setTimeout(15000)
/** this code is called once before any test is called */
beforeAll(async done => {
  await setupStrapi(); // singleton so it can be called many times
  done();
});

/** this code is called once before all the tested are finished */
afterAll(async done => {
  const dbSettings = strapi.config.get('database.connections.default.settings');

  //delete test database after all tests
  if (dbSettings && dbSettings.filename) {
    const tmpDbFile = `${__dirname}/../${dbSettings.filename}`;
    if (fs.existsSync(tmpDbFile)) {
      fs.unlinkSync(tmpDbFile);
    }
  }
  done();
});

it('strapi is defined', () => {
  expect(strapi).toBeDefined();
});

Any help would be greatly appreciated. Thanks

2 Likes

I had the same problem. And I found out by looking at the GitHub core repo. That we should use :

//close server to release the db-file
  await strapi.server.close();

instead:

//close server to release the db-file
  await strapi.destroy();
2 Likes

Thank you for your help, this took me almost 2 hours wondering to know where the bug was comming from. Thank you a lot

For me even after this change i still have the same problem like this didn’t work for me and the db-file still busy
resource busy or locked, unlink 'C:\Users\DELL\Documents\gomycode\website-strapi-backend\tests/…/.tmp/test.db