如何用Jest模拟外部模块的功能 [英] How to mock an external module's function with Jest
问题描述
Jest的模拟可以处理我未编写的模块中的功能吗?
Can Jest's mocking handle functions from modules I didn't write?
node-yelp-api-v3 具有Yelp.searchBusiness(String)
,但是我尝试使用 Jest的模拟功能失败. Jest示例似乎假设我正在模拟项目中具有的模块.从文档中,我还不清楚如何在模块中模拟特定功能.
node-yelp-api-v3 has Yelp.searchBusiness(String)
but my attempts to use Jest's mocking functionality are unsuccessful. The Jest examples seem to assume that I'm mocking a module I have in the project. From the documentation I'm also unclear how to mock a specific function in a module.
这些都不起作用:
jest.mock('Yelp.searchBusiness', () => {
return jest.fn(() => [{<stubbed_json>}])
})
或
jest.mock('Yelp', () => {
return jest.fn(() => [{<stubbed_json>}])
})
我当前正在使用sinon
,但只想使用Jest.希诺这种方法有效:
I'm currently using sinon
but would like to use just Jest. This Sinon approach works:
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()
})
})
})
推荐答案
模拟外部模块的说明此处.
如果您要模拟的模块是节点模块(例如:
lodash
),则模拟应放置在与node_modules
相邻的__mocks__
目录中(除非您将根配置为指向除项目根目录),并将被自动嘲笑.无需显式调用jest.mock('module_name')
.
If the module you are mocking is a Node module (e.g.:
lodash
), the mock should be placed in the__mocks__
directory adjacent tonode_modules
(unless you configured roots to point to a folder other than the project root) and will be automatically mocked. There's no need to explicitly calljest.mock('module_name')
.
对于您的确切情况,这意味着您需要创建其中包含文件node-yelp-api-v3.js
的文件夹__mocks__
.在该文件中,您可以使用 genMockFromModule
从原始模块中创建一个模拟对象.并覆盖您要模拟的方法.
For your exact case this would mean you need to create a folder __mocks__
with a file node-yelp-api-v3.js
in it. In that file you create a mock object from the original module using genMockFromModule
and override the method you want to mock.
// __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
中.
Additionally you could also wrap the searchBusiness
in jest.fn
if you want to call assertions like searchBusiness.mock.calls.length
for this method later.
这篇关于如何用Jest模拟外部模块的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!