问题
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;
};
and then check tables existence (and create them) with
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
}
}
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: 'test@test.com'
});
expect(res.statusCode).toEqual(200);
done();
})
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.
回答1:
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.
来源:https://stackoverflow.com/questions/46534802/jest-test-are-run-before-db-is-ready