我有一个路由器功能可以做到这一点:
let note = await db.sequelize.knex.raw(
'UPDATE notes '
+ 'SET note = ?, '
+ 'timestamp = NOW() '
+ 'FROM(SELECT id, '
+ 'note, '
+ 'user_id, '
+ 'customer_id, '
+ 'product_id, '
+ 'timestamp '
+ 'FROM notes '
+ 'WHERE id = ? '
+ 'AND user_id = 7) AS a '
+ 'LEFT JOIN customers AS b ON a.customer_id = b.id '
+ 'LEFT JOIN products AS c ON a.product_id = c.id '
+ 'WHERE notes.id = a.id '
+ 'RETURNING a.id, '
+ 'notes.note, '
+ 'notes.user_id AS "userId", '
+ 'notes.customer_id AS "customerId", '
+ 'notes.product_id AS "productId", '
+ 'notes.timestamp, '
+ 'b.title AS "customerName", '
+ 'b.code AS "customerCode", '
+ 'c.title AS "productName", '
+ 'c.code AS "productCode"', [newNote, noteId],
);
[note] = note.rows;
return res.json({ note });
当我手动测试时,我在响应中看到更新的注释,并且对数据库的查询显示注释已针对相关记录进行了更新。
我也有这个测试:
it('should update a note', (done) => {
chai.request(apiAddress)
.patch('/api/supplier/notes/1')
.send('{"note":"mynote"}')
.set('Authorization', AuthToken)
.set('Content-Type', 'application/json')
.set('Origin', originAddress)
.then((res) => {
res.should.have.status(200);
res.type.should.eql('application/json');
})
.then(() => (
db.sequelize.knex.select()
.from('notes')
.where('id', 1)
))
.then((notes) => {
expect(notes).to.have.lengthOf(1);
expect(notes[0]).to.deep.include({
note: 'mynote',
});
done();
})
.catch((err) => {
done(err);
});
});
失败:
expect(notes[0]).to.deep.include({
note: 'mynote',
});
在我看来,更新笔记测试的检查是在笔记实际上在数据库上更新之前完成的。我怎样才能解决这个问题?我主张增加等待时间,但宁愿避免这种情况。