gpt4 book ai didi

javascript - 在 Jest 中使用 'new' 关键字模拟外部服务

转载 作者:行者123 更新时间:2023-11-30 20:32:37 25 4
gpt4 key购买 nike

我无法正确模拟使用 new 关键字实际返回我在 Jest 测试中想要的内容的模块。

我的函数是这样的:

 'myService.js'

export const checkMayFlyRecord = record => {
return new Promise((resolve, reject) => {
const recId = crypto.createHash('md5').update(record.id + record.url).digest('hex')

const mayflyClient = new mayfly({
appName: 'cartrecoverynodeserv',
lifetime: 24 * 3600, // store for 24 hours
crypto: false
})

mayflyClient.read(recId, (err, response) => {
console.log('yo dog')
if (err) {
reject(err)
} else if (response.status && response.status > 0) {
mayflyClient.set(recId, JSON.stringify(record), (err, response) => {
if (err) {
reject(err)
} else if (response.status && response.status > 0) {
reject(err)
}
resolve('saved')
})
} else {
resolve('found')
}
})
})
}

我的测试是这样的:

/* global jest, describe, beforeAll, beforeEach, expect, test */

describe('myService', () => {
let mayfly
let dropoffsService
let mayflyFunctions
const records = [
{'id': '2024876599037241006', 'url': 'jey.com'}
]

beforeAll(() => {
mayfly = jest.genMockFromModule('mayfly')
jest.mock('mayfly')
mayfly = require('mayfly')

mayfly.read = jest.fn().mockReturnValue({ status: 1 })
mayfly.set = jest.fn().mockReturnValue({ status: 1 })

// mayflyFunctions = {
// set: jest.fn().mockReturnValue({ status: 1 }),
// read: jest.fn().mockReturnValue({ status: 1 })
// }
//
// mayfly.mockImplementation(() => { mayflyFunctions })

myService = require('./myService')
})

describe('checkMayFlyRecord', () => {
test.only('mayfly calls the read function when connection is made', async () => {
await myService.checkMayFlyRecord(records[0])
expect(mayflyFunctions.read).toHaveBeenCalled()
})
})
})

按原样进行测试,出现以下错误:超时 - 在 jest.setTimeout 指定的 5000 毫秒超时内未调用异步回调。

但是,如果我删除 jest.mock('mayfly'),然后我到达我的 yo dog 控制台日志,并且出现连接错误。这告诉我,我一定是在模拟第三方模块 mayfly 的方式上做错了。通常,这很容易,但这是我第一次不得不模拟一个必须使用 new 关键字的模块。

您会注意到注释掉了,我已经尝试使用 jest 的 mockImplementation() 函数,但也无法正常工作。

有人看到我做错了什么吗?

最佳答案

我认为您的模拟方法需要调用传递给它们的回调。尝试:

mayfly.read = jest.fn((recordId, callback) => {
callback(undefined, {
status: 200
})
})

关于javascript - 在 Jest 中使用 'new' 关键字模拟外部服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50180062/

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