我对自动化测试相当陌生,想知道我应该如何为数据库编写测试。我现在正在处理的项目是在 Node.JS 环境中运行带有 Sequelize 作为 ORM 的 PostgreSQL。如果重要的话,我现在还使用 Jest 作为测试库。
最佳答案
在我的应用程序中,我使用 config
模块来控制不同环境的配置设置。运行测试时,process.env.APP_ENV
设置为 test
,它会将 dialect
设置为 sqlite
.请注意,您将没有任何数据或数据持久性,因此您需要使用测试所需的所有数据填充它。
包含sqlite3
yarn add -D sqlite3
或
npm i -D sqlite3
配置
module.exports = {
database: {
name: 'dbname',
user: 'user',
password: 'password',
host: 'host',
// Use "sqlite" for "test", the connection settings above are ignored
dialect: process.env.APP_ENV === 'test' ? 'sqlite' : 'mysql',
},
};
数据库/Sequelize
// get our config
const config = require('../config');
// ... code
const instance = new Sequelize(
config.database.name,
config.database.user,
config.database.password,
{
host: config.database.host,
// set the dialect, will be "sqlite" for "test"
dialect: config.database.dialect,
}
);
测试类(摩卡)
const TestUtils = require('./lib/test-utils');
describe('Some Tests', () => {
let app = null;
// run before the tests start
before((done) => {
// Mock up our services
TestUtils.mock();
// these are instantiated after the mocking
app = require('../server');
// Populate redis data
TestUtils.populateRedis(() => {
// Populate db data
TestUtils.syncAndPopulateDatabase('test-data', () => {
done();
});
});
});
// run code after tests have completed
after(() => {
TestUtils.unMock();
});
describe('/my/route', () => {
it('should do something', (done) => {
return done();
});
});
});
运行测试
APP_ENV=test ./node_modules/.bin/mocha
您也可以通过其他方式使用 ENV 变量来设置方言和连接参数 - 以上只是基于我们使用大量支持代码完成的示例。
关于node.js - 使用数据库进行自动化测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46759668/