【问题标题】:How to mock an external module's function with Jest如何使用 Jest 模拟外部模块的功能
【发布时间】:2018-01-18 22:02:34
【问题描述】:

Jest 的模拟可以处理我没有编写的模块中的函数吗?

node-yelp-api-v3Yelp.searchBusiness(String) 但我尝试使用 Jest's mocking functionality 没有成功。 Jest 示例似乎假设我在模拟项目中的一个模块。从文档中我也不清楚如何模拟模块中的特定功能。

这些都不起作用:

jest.mock('Yelp.searchBusiness', () => {
  return jest.fn(() => [{<stubbed_json>}])
})

jest.mock('Yelp', () => {
  return jest.fn(() => [{<stubbed_json>}])
})

我目前正在使用sinon,但只想使用 Jest。这种 Sinon 方法有效:

var chai = require('chai')
var should = chai.should()
var agent = require('supertest').agent(require('../../app'))

const Yelp = require('node-yelp-api-v3')

var sinon = require('sinon')
var sandbox

describe('router', function(){
  beforeEach(function(){
    sandbox = sinon.sandbox.create()
    stub = sandbox.stub(Yelp.prototype, 'searchBusiness')
  })

  afterEach(function(){
    sandbox.restore()
  })

  it ('should render index at /', (done) => {
    /* this get invokes Yelp.searchBusiness */
    agent
      .get('/')
      .end(function(err, res) {
        res.status.should.equal(200)
        res.text.should.contain('open_gyro_outline_500.jpeg')

        done()
      })
  })
})

【问题讨论】:

    标签: jestjs


    【解决方案1】:

    模拟外部模块解释here

    如果您要模拟的模块是 Node 模块(例如:lodash),则模拟应放置在与 node_modules 相邻的 __mocks__ 目录中(除非您将根配置为指向除项目根目录)并将自动模拟。无需显式调用jest.mock('module_name')

    对于您的具体情况,这意味着您需要创建一个文件夹 __mocks__,其中包含一个文件 node-yelp-api-v3.js。在该文件中,您使用 genMockFromModule 从原始模块创建一个模拟对象并覆盖您要模拟的方法。

    // __mocks__/node-yelp-api-v3.js
    
    const yelp = jest.genMockFromModule('node-yelp-api-v3')
    
    function searchBusiness() {
        return [{<stubbed_json>}]
    }
    
    yelp.searchBusiness = searchBusiness
    
    module.exports = yelp
    

    此外,如果您想稍后为此方法调用像searchBusiness.mock.calls.length 这样的断言,您还可以将searchBusiness 包装在jest.fn 中。

    【讨论】:

    • 谢谢@brass猴子。你应该在 Jest 文档中提出 PR
    【解决方案2】:

    您也可以这样做:

    jest.mock('Yelp', () => ({
        searchBusiness: jest.fn(() => [{<stubbed_json>}])
    })
    

    然后你就可以调用诸如 expect(Yelp.searchBusiness).toHaveBeenCalled() 之类的东西了。

    【讨论】:

      猜你喜欢
      • 2019-08-28
      • 2019-07-16
      • 2019-09-18
      • 2023-03-11
      • 2019-08-10
      • 1970-01-01
      • 2018-08-07
      • 2018-01-26
      • 2022-06-30
      相关资源
      最近更新 更多