代码之家  ›  专栏  ›  技术社区  ›  AJ.

如何在JavaScript集成测试中验证MySQL行创建日期?

  •  1
  • AJ.  · 技术社区  · 6 年前

    我正在为使用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!!
    
    0 回复  |  直到 6 年前
        1
  •  1
  •   VPaul    6 年前

    created_at (从服务器)小于 now

    为了解决这个问题,我们可以把精度传递给矩量 isSameOrAfter https://momentjscom.readthedocs.io/en/latest/moment/05-query/05-is-same-or-after/ )了解如何将精度传递给此函数。

        2
  •  0
  •   Teneff    6 年前

    不使用momentjs,您可以尝试使用unix时间戳,MySQL(以秒为单位)和javascript(以毫秒为单位)都支持unix时间戳

    test('difference in time should be within a second', () => {
      x = query("SELECT UNIX_TIMESTAMP(created_at) AS x FROM ...");
      expect(x).toBeCloseTo(Date.now() / 1000, 0);
    });
    
    推荐文章