如何使用 Jest 模拟外部模块的功能

eeb*_*sen 6 jestjs

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

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

这些都不起作用:

jest.mock('Yelp.searchBusiness', () => {
  return jest.fn(() => [{<stubbed_json>}])
})
Run Code Online (Sandbox Code Playgroud)

或者

jest.mock('Yelp', () => {
  return jest.fn(() => [{<stubbed_json>}])
})
Run Code Online (Sandbox Code Playgroud)

我目前正在使用,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()
      })
  })
})
Run Code Online (Sandbox Code Playgroud)

Laz*_*ass 6

这里解释模拟外部模块。

如果您lodash模拟的模块是 Node 模块(例如:),则模拟应放置在__mocks__相邻的目录中node_modules(除非您将根配置为指向项目根以外的文件夹),并且将自动进行模拟。无需显式调用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
Run Code Online (Sandbox Code Playgroud)

此外searchBusinessjest.fn如果您想searchBusiness.mock.calls.length稍后为此方法调用断言,您也可以将in包装起来。