对React中MobX商店测试方法的反馈



我是用Jest在React中测试MobX商店的新手。我读过这个和这个,但这些帖子专注于用商店测试组件,而不是商店本身

与Jest隔离对商店进行单元测试的最佳方法是什么?

我最初的想法是实例化类(新的EpochManager(,然后调用方法来更改存储的状态,但抛出了一个TypeErrorTypeError: _EpochManager.default is not a constructor。这可能表明了我对MobX的天真。

例如,这里有一个我希望进行单元测试的商店:

import { createContext } from 'react'
import UnirepContext from './Unirep'
import UserContext from './User'
import { makeAutoObservable } from 'mobx'
const unirepConfig = (UnirepContext as any)._currentValue
const userContext = (UserContext as any)._currentValue
class EpochManager {
private timer: NodeJS.Timeout | null = null
private currentEpoch = 0
readonly nextTransition = 0
readyToTransition = false
constructor() {
makeAutoObservable(this)
if (typeof window !== 'undefined') {
this.updateWatch()
}
}
async updateWatch() {
await unirepConfig.loadingPromise
if (this.timer) {
clearTimeout(this.timer)
this.timer = null
}
this.readyToTransition = false
this.currentEpoch = await unirepConfig.currentEpoch()
// load the last transition time
;(this as any).nextTransition = await this._nextTransition()
const waitTime = Math.max(this.nextTransition - +new Date(), 0)
console.log(
`Next epoch transition in ${waitTime / (60 * 60 * 1000)} hours`
)
this.timer = setTimeout(() => {
this.timer = null
this.tryTransition()
}, waitTime) // if it's in the past make wait time 0
return waitTime
}
private async _nextTransition() {
await unirepConfig.loadingPromise
const [lastTransition, epochLength] = await Promise.all([
unirepConfig.unirep.latestEpochTransitionTime(),
unirepConfig.epochLength,
])
return (lastTransition.toNumber() + epochLength) * 1000
}
private async tryTransition() {
// wait for someone to actually execute the epoch transition
for (;;) {
// wait for the epoch change to happen
const newEpoch = await userContext.loadCurrentEpoch()
if (newEpoch > this.currentEpoch) {
// we're ready to transition,
this.currentEpoch = newEpoch
this.readyToTransition = true
return
}
await new Promise((r) => setTimeout(r, 10000))
}
}
}
export default createContext(new EpochManager())

EpochManager类有一个命名导出:

export class EpochManager { ....

在测试中导入时:

import { EpochManager } from '..context/EpochManager

然后,实例化该类并进行一些测试。

最新更新