本文介绍了在 DB 准备好之前运行 Jest 测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Jest 用 SQLite 数据库测试我的 express API,但出现了以下问题 - 在数据库准备好并创建表之前运行测试.

I am using Jest to test my express API with SQLite database, but the following problem appeared - test are run before DB is ready and tables are created.

我使用以下代码连接到数据库:

I connect to DB with following code:

const connectToDatabase = () => {
  let db;
  if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'production') {
    db = new sqlite3.Database('task_list');
  } else if (process.env.NODE_ENV === 'test') {
    db = new sqlite3.Database(':memory:');
  } else {
    throw new Error('Environment is not defined!');
  }
  db.pRun = promisify(db.run, db);
  db.pGet = promisify(db.get, db);
  db.pAll = promisify(db.all, db);
  db.pClose = promisify(db.close, db);
  return db;
};

然后使用

const prepareTables = async (db) => {
  // check existence of 'users' table
  try {
    const usersTable = await db.pGet("SELECT name FROM sqlite_master WHERE type='table' AND name='users'");
    if (!usersTable) {
      // create table
      db.pRun(`
        CREATE TABLE users (
          id TEXT,
          username TEXT,
          email TEXT,
          password TEXT
        )
      `);
    }
  } catch (err) {
    console.log('error', err); // eslint-disable-line no-console
  }
}

然后导出数据库以在 API 方法中使用.我的方法是:

and then export DB for using in API methods. My method is:

const createUser = async (req, res) => {
  // create user
  try {
    const newUser = {
      id: uuid.v4(),
      username: req.body.username,
      email: req.body.email,
      password: bcrypt.hashSync(req.body.password)
    }
    await db.pRun(`
      INSERT INTO USERS (id, username, email, password)
      VALUES (
        "${newUser.id}",
        "${newUser.username}",
        "${newUser.email}",
        "${newUser.password}"
      )
    `);
    const response = await db.pGet(`SELECT * FROM users WHERE id='${newUser.id}'`);
    delete response.password;
    res.status(200).send(response);
  } catch (err) {
    console.log(err); // eslint-disable-line no-console
    res.status(500).send("Unlucky, database error.");
  }
}

当服务器启动时它工作正常,我通过邮递员手动调用它.但我的测试:

And it works fine when server is started and I manually call it via Postman. But my test:

it('should create new user', async (done) => {
    const res = await request(app)
      .post('/api/users/')
      .send({
        username: 'username',
        password: 'password',
        email: '[email protected]'
      });
    expect(res.statusCode).toEqual(200);
    done();
  })

抱怨没有创建表是行不通的.我控制台记录了数据库,这是真的.看起来在服务器成功启动和表格格式化之前调用了 API.我使用内存数据库,所以每次都需要格式化.任何建议如何实现所需的行为?谢谢.

Doesn't work complaining about tables aren't created. I console logged db and it's true. Looks like API is being called before server successfully started and tables are formatted. I use in-memory DB, so it needs to be formatted every time.Any suggestions how to achieve desired behavior?Thanks.

推荐答案

我应该仔细阅读 Jest 文档,有一个 option 适合我的情况.我将带有数据库初始化的文件添加到 package.json 中的setupFiles"数组中,它工作正常.

I should read Jest docs carefully, there is an option right for my case.I added file with DB initialization to "setupFiles" array in my package.json and it works fine.

这篇关于在 DB 准备好之前运行 Jest 测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 05:42