gpt4 book ai didi

node.js - 当模拟 es6 类时,Jest 无法读取未定义的属性 'instances'

转载 作者:太空宇宙 更新时间:2023-11-03 22:23:54 25 4
gpt4 key购买 nike

尝试模拟 ES6 类,只是为了获得一个我可以监视的虚拟模拟。我的代码似乎非常严格地遵循文档,但是在我的虚拟对象上调用 .mock 时出现此错误:

TypeError: Cannot read property 'instances' of undefined

jest.mock('../../../adapters/Cache')
const Fizz = require('../Fizz')
const Cache = require('../../../adapters/Cache')

const fizz = new Fizz()

describe('CACHE', () => {
it('should return a mock', () => {
//This is the line that fails
const mockCache = Cache.mock.instances[0]

const mockRetrieveRecords = mockCache.retrieveRecords
fizz.doStuff()
expect(mockRetrieveRecords).toHaveBeenCalledTimes(1)
})
})

最佳答案

jest.mock('../../../adapters/Cache') 将仅使用 undefined 来模拟模块。要模拟返回类的模块,您可以创建一个仅返回一个返回模拟实例的函数的模拟。要设置使 retrieveRecords 成为您可以在测试中访问的 spy ,您必须使用空 spy 模拟该模块,导入它并设置真正的模拟:

jest.mock('../../../adapters/Cache', () => jest.fn())
const Cache = require('../../../adapters/Cache')
const Fizz = require('../Fizz')

const retrieveRecords = jest.fn()
Cache.mockImplementation(() => ({retrieveRecords})



describe('CACHE', () => {
it('should return a mock', () => {
const fizz = new Fizz()
fizz.doStuff()
expect(retrieveRecords).toHaveBeenCalledTimes(1)
})
})

关于node.js - 当模拟 es6 类时,Jest 无法读取未定义的属性 'instances',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49564103/

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