#javascript #fixtures #ui-testing #jest-puppeteer
Вопрос:
Кто-нибудь использовал приспособления (файл json) для загрузки данных в базу данных postgres и выполнения тестирования пользовательского интерфейса ?
Ответ №1:
С помощью потоков node-postgres и node-pg-копирования можно загружать и удалять/удалять данные из базы данных postgres. Код и пример: [https://github.com/AmitKulkarni9/fixtures-tests][1]
LoadData.js
const fs = require('fs');
const path = require('path');
const {Client} = require('pg');
const copyFrom = require('pg-copy-streams').from;
const config = require('./config.json');
// Getting connection parameters from config.json
const host = config.host;
const user = config.user;
const pw = config.pw;
const db = config.db;
const port = config.port;
const conString = `postgres://${user}:${pw}@${host}:${port}/${db}`;
class LoadData {
async Load (targetTable) {
try {
const inputFile = path.join(__dirname, `/data/${targetTable}.csv`);
const client = new Client({connectionString: conString,});
client.connect(); // gets connection
const stream = client.query(copyFrom(`COPY ${targetTable} FROM STDIN WITH CSV HEADER`));
const fileStream = fs.createReadStream(inputFile);
fileStream.on('error', (error) =>{
console.log(`Error in creating read stream ${error}`);
client.end();
return;
})
stream.on('error', (error) => {
console.log(`Error in creating stream ${error}`);
client.end();
return;
})
stream.on('finish', () => {
console.log(`Completed loading data into ${targetTable}`);
client.end();
})
fileStream.pipe(stream);
return;
} catch (e) {
console.error(e);
client.end();
return;
}
}
}
module.exports = LoadData;
RemoveData.js
const path = require('path');
const {Client} = require('pg');
const config = require('./config.json');
// Getting connection parameters from config.json
const host = config.host;
const user = config.user;
const pw = config.pw;
const db = config.db;
const port = config.port;
const conString = `postgres://${user}:${pw}@${host}:${port}/${db}`;
class RemoveData {
async Remove (table) {
try {
const client = new Client({connectionString: conString,});
client.connect(); // gets connection
client.query(`DELETE FROM ${table} WHERE id IN ($1,$2,$3) RETURNING *`, [1,2,3], (err, result) => {
if(err) {
console.log(err);
client.end();
return;
} else {
console.log(`Deleted data from ${table}`);
//let results= result.rows;
//console.log(results);
client.end();
return;
}
});
} catch (e) {
console.error(e);
client.end();
return;
}
}
}
module.exports = RemoveData;