【问题标题】:mock moment.js in node using jest使用 jest 在节点中模拟 moment.js
【发布时间】:2019-03-11 17:55:59
【问题描述】:

我正在尝试模拟 moment.js 以预测我的集成测试。
我一直在尝试像this 一样模拟jest

import moment from 'moment'
...
jest.mock('moment', () => () => ({valueOf: () => 100})

但是当我运行我的测试时,源代码使用的是普通的moment

我已经通过 this 成功覆盖了 moment 行为,但这还不够好,因为它覆盖了更多我不想更改的功能。

【问题讨论】:

    标签: javascript unit-testing jestjs momentjs


    【解决方案1】:

    当我必须模拟 moment.js 函数时,我使用来自 Sinon.js (https://sinonjs.org/releases/v7.2.7/stubs/) 的 stubs 来模拟。

    基本上是这样的:

    import * as sinon from 'sinon'
    import moment from 'moment'
    ...
    const stubValueOf = sinon.stub(moment, 'valueOf');
    stubValueOf.returns(100);
    

    重要提示:使用存根的一个好习惯是仅将它用于特定测试而不是整个测试文件。因此,每次使用后,请使用stubValueOf.restore()。如果您想在同一个测试中使用不同的值“存根”该方法,请使用stubValueOf.reset()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-14
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 1970-01-01
      相关资源
      最近更新 更多