gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:49:35 27 4
gpt4 key购买 nike

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()
})
})
})

最佳答案

模拟外部模块解释 here .

If the module you are mocking is a Node module (e.g.: lodash), the mock should be placed in the __mocks__ directory adjacent to node_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 call 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

此外,您还可以包装 searchBusinessjest.fn如果你想调用 searchBusiness.mock.calls.length 之类的断言以后用这个方法。

关于jestjs - 如何使用 Jest 模拟外部模块的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45617362/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com