我正在为使用MySQL数据库的节点数据访问模块中的“create”方法编写一个集成测试。我们的MySQL表有一个
created_at
timestamp
默认为
CURRENT_TIMESTAMP
. 假设我的桌子看起来像这样:
CREATE TABLE `some_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`column1` varchar(255) DEFAULT NULL,
`column2` int(11) DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
)
我想做的是测试
字段的设置与测试开始执行时相同或相同。我试着利用瞬间的力量
isSameOrAfter
有了它
utc()
test('created_at is set on creation', async () => {
// must use UTC since CURRENT_TIMESTAMP is UTC
const now = moment.utc();
// newObject is a POJO of the newly created row in some_table
const newObject = await someTableLib.create(args);
// this does not work for some reason
expect(moment.utc(newObject.created_at).isSameOrAfter(now)).toBe(true);
})
我也试过不使用
utc()
要分析数据库日期:
expect(moment(newObject.created_at).isSameOrAfter(now)).toBe(true);
如何才能最好地测试数据库的设置
创建于
如预期的那样?
编辑
当我抛出一些
console.log()
语句(尽管我不确定如何最好地比较
console.log
):
console.log(newObject.created_at);
// 2020-04-08T14:50:46.000Z
console.log(moment.utc(newObject.created_at).format('YYYY-MM-DD HH:mm:ss');
// 2020-04-08 14:50:46
console.log(now.format('YYYY-MM-DD HH:mm:ss');
// 2020-04-08 14:50:46
我现在完全糊涂了。如果我格式化力矩对象,然后将它们重新初始化为力矩对象,然后比较它们,它就起作用了:
const testStart = moment(now.format('YYYY-MM-DD HH:mm:ss'));
const created = moment(moment.utc(newObject.created_at).format('YYYY-MM-DD HH:mm:ss'));
expect(created.isSameOrAfter(testStart)).toBe(true); // this passes!!