【问题标题】:Mocking Modules in JestJest 中的模拟模块
【发布时间】:2020-07-17 18:11:10
【问题描述】:

我在 App.js 中有一个方法,我想为其编写测试用例。但是,当我在测试文件中导入 App.js 时,App.js 中的所有导入语句也会被导入并导致错误。是否可以模拟使用 jest 在我的 App.js 中导入的依赖项。考虑下面的例子

//App.js 
import user from '../user.js';
//some functions which needs to be tested

在我的 App.spec.js 文件中尝试时是否可以模拟 user.js ?

【问题讨论】:

    标签: javascript unit-testing mocking jestjs


    【解决方案1】:

    你可以使用 sinonjs https://sinonjs.org/how-to/stub-dependency/

    sinon.stub(user, 'functionToMock').callsFake(() => {})

    【讨论】:

      【解决方案2】:

      您可以通过以下语句简单地模拟任何用户模块。

      jest.mock('./moduleName') 
      

      为了进一步了解,您可以参考以下文档。

      https://jestjs.io/docs/en/manual-mocks#:~:text=When%20a%20manual%20mock%20exists,moduleName'

      【讨论】:

        猜你喜欢
        • 2019-08-17
        • 2019-12-26
        • 1970-01-01
        • 1970-01-01
        • 2021-02-04
        • 2017-02-23
        • 1970-01-01
        • 2021-09-07
        • 2019-07-16
        相关资源
        最近更新 更多