开玩笑虚拟模拟:如何解决此故障?



所以我在一个模块中有这个导入语句,我正在尝试使用节点 25.1.1 上运行的 jest 11.1.0 进行测试。import 语句适用于仅在 jvm 的 nashorn 运行时运行时可用的模块,因此我使用 jest 的虚拟模拟来控制单元测试中的行为。下面是 import 语句在所测试模块中的样子:

import RequestBuilder from 'nashorn-js/request_builder'

。在导入块中的其他行之后,这:

const request = RequestBuilder.create('some-string')
.sendTo('some-other-string')
.withAction('yet-another-string')
.getResultWith( consumer => consumer.result( consumer.message().body() ) )
export const functionA = () => {...} // uses 'request' variable
export const functionB = () => {...} // uses 'request' variable

在相应的 .spec 文件中,我有这个虚拟模拟设置:

const mockGetResultWith = {
getResultWith: jest.fn()
}
const mockWithAction = {
withAction: jest.fn().mockImplementation(() => mockGetResultWith)
}
const mockSendTo = {
sendTo: jest.fn().mockImplementation(() => mockWithAction)
}
const mockBuilder = {
create: jest.fn().mockImplementation(() => mockSendTo)
}
jest.mock(
'nashorn-js/request_builder',
() => mockBuilder,
{ virtual: true }
)
require('nashorn-js/request_builder')
import { functionA, functionB } from './module-under-test'

我一直试图从开玩笑中摆脱这个失败,但没有成功:

● Test suite failed to run
TypeError: Cannot read property 'create' of undefined
35 | }
36 | 
> 37 | const verify = RequestBuilder.create('some-string')
|                               ^
38 | .sendTo('some-other-string')
39 | .withAction('yet-another-string')
40 | .getResultWith( consumer => consumer.result( consumer.message().body() ) )

我尝试了各种不同的模拟结构,使用requirevsimport等,但没有找到灵丹妙药。

据我所知,RequestBuilderimport 语句似乎甚至没有调用虚拟模拟。或者至少,如果我将console.log()语句添加到虚拟模拟工厂函数,我永远不会在输出中看到这些日志消息。

有人知道我错过了什么或还有什么可以尝试的吗?我在代码的其他部分使用了几乎相同的模式,这个设置在哪里工作,但由于这个模块的一些神秘原因,我无法让虚拟模拟工作。任何帮助将不胜感激。

所以,这里的问题原来是 jest 在 .spec 文件中实现importrequire

通过更改此行:

import { functionA, functionB } from './module-under-test'

对此:

const module = require('./module-under-test')
const functionA = module.functionA
const functionB = module.functionB

受测模块现在已成功加载,并且测试按预期运行。

我对此没有任何解释,也无法找到开玩笑的文档来描述为什么我会在requireimport之间得到任何不同的行为。实际上,我在任何import语句之前都有模拟配置设置,如下所述:

https://github.com/kentcdodds/how-jest-mocking-works

如果有人了解这种import行为是怎么回事,或者有一个链接描述我错过了什么,我肯定会不胜感激。

最新更新