我有一个SQL查询,当我在我的PostgreSQL数据库中直接使用它时,它似乎工作得很好,但是我很难让它通过我的磁带测试,因为预期的输出不是我所期望的。
我已经将实际的查询粘贴到pgcli/数据库接口中,它运行得很好。
const findAllFoodItems = cb => {
dbConnection.query(
'SELECT products.name, categories.name FROM products INNER JOIN categories ON products.category_id = categories.id;',
(err, res) => {
if (err) {
cb(err);
} else {
cb(null, res.rows);
}
}
)
}
module.exports = { findAllFoodItems }test("Check findAllFoodItems queries correctly", t => {
findAllFoodItems((err, res) => {
if(err) {
t.error(err, "Unable to findAllFoodItems");
t.end();
} else {
const expected = [{"Banana": "Fruit"}, {"Potato": "Vegetables"}, {"Sausages": "Meat"}, {"Apple": "Fruit"}];
t.deepEquals(res, expected);
t.end();
}
})
});SELECT products.name, categories.name
FROM products
INNER JOIN categories ON products.category_id = categories.id;产出:
+----------+------------+
| name | name |
|----------+------------|
| Banana | Fruit |
| Potato | Vegetables |
| Sausages | Meat |
| Apple | Fruit |
+----------+------------+磁带/测试失败报告:
operator: deepEqual
expected: |-
[ { Banana: 'Fruit' }, { Potato: 'Vegetables' }, { Sausages: 'Meat' }, { Apple: 'Fruit' } ]
actual: |-
[ { name: 'Fruit' }, { name: 'Vegetables' }, { name: 'Meat' }, { name: 'Fruit' } ]发布于 2019-09-10 22:51:56
第一个问题是,您的查询返回的两个列都有相同的名称(即name)。Postgres很高兴地处理这个问题,但是这可能会导致客户端的歧义,特别是当它使用列名作为键时,这里似乎就是如此。您需要将结果集中的列化名为:
SELECT products.name pname, categories.name cname FROM ...第二个问题是你的预期结果是不正确的。您的驱动程序似乎返回一个键/值对数组,其中键是列名。因此,您应该检查以下输出:
[
{ pname: 'Banana', cname: 'Fruit' },
{ pname: 'Potato', cname: 'Vegetables' },
{ pname: 'Sausages', cname: 'Meat' },
{ pname: 'Apple', cname: 'Fruit' }
]https://stackoverflow.com/questions/57879042
复制相似问题