gpt4 book ai didi

javascript - 如何访问从模拟库返回的模拟方法

转载 作者:行者123 更新时间:2023-12-02 22:53:37 25 4
gpt4 key购买 nike

我正在模拟@elastic/elasticsearch库,我想测试是否使用正确的参数调用了search方法,但是在从测试中访问search时遇到了问题。
在我的ES模拟中,我只是导出一个包含Client Prop 的对象,该对象返回另一个具有search Prop 的对象。这是从库访问search的方式

const { Client } = require('@elastic/elasticsearch')
const client = new Client(...)
client.search(...)
__mocks __ / @ elastic / elasticsearch
module.exports = {
Client: jest.fn().mockImplementation(() => {
return {
search: (obj, cb) => {
return cb(
'',
{
statusCode: 200,
body: {
hits: {
hits: [
{
_source: esIndexes[obj.index]
}
]
}
}
}
)
}
}
})
}
__tests __ / getAddresses.test.js
const { getAddresses } = require('../src/multiAddressLookup/utils/getAddresses')
const { Client } = require('@elastic/elasticsearch')

beforeEach(() => {
process.env.ES_CLUSTER_INDEX = 'foo'
process.env.ui = '*'
})

describe('multiAddressLookup', () => {
test('Should return the correct premises data with only the relevant "forecasted_outages"', async () => {
const event = {
foo: 'bar'
}
const esQueryResponse = {
"body": "\"foo\":\"bar\"",
"headers": {"Access-Control-Allow-Origin": '*'},
"statusCode": 200
}

await expect(getAddresses(event)).resolves.toEqual(esQueryResponse)
expect(Client().search).toHaveBeenCalled() // This fails with 0 calls registered
})
})

最佳答案

我不确定这种情况的确切文档,但是在查看Jest文档的Jest: The 4 ways to create an ES6 Mock Class - Automatic mock部分时我就知道了。
首先,需要将ES模拟中的search方法__mocks__/@elastic/elasticsearch转换为一个简单的模拟函数jest.fn()。这样做使我们可以访问 Jest 模拟所提供的属性和值。
__mocks__/@elastic/elasticsearch.js 转换

module.exports = {
Client: jest.fn().mockImplementation(() => {
return {
search: jest.fn((obj, cb) => {
return cb(
'',
{
statusCode: 200,
body: {
hits: {
hits: [
{
_source: esIndexes[obj.index]
}
]
}
}
}
)
})
}
})
}
其次,在测试中,我们需要遵循 Client模拟类的路径,直到找到方法为止。语法为 MockClass.mock.results[0].value.mockFunction
示例测试
const { Client } = require('@elastic/elasticsearch')  // This is located in the "__mocks__" folder in the root of your project

const { getAddresses } = require('../../src/getAddresses') // This is the file we wrote and what we are unit testing

describe('getAddresses', () => {
it('Should call the ES Search method', async () => {
const event = { ... }
const expected = { ... }
await expect(getAddresses(event)).resolves.toEqual(expected) // pass
expect(Client.mock.results[0].value.search).toHaveBeenCalled() // pass
})
})

关于javascript - 如何访问从模拟库返回的模拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63140083/

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