如何在 React today.getFullYear() + 1 中进行测试

How to test in react today.getFullYear() + 1

我想在 React 中测试以下代码行:

const today = new Date()
export const nextYear = today.getFullYear() + 1

我尝试过的:

import { nextYear } from '../nextYear'
import MockDate from 'mockdate'

describe('NextYearHelper', () => {
  describe('nextYear', () => {
    it('returns next year', () => {
      MockDate.set('2030-11-22')
      expect(nextYear).toEqual(2031)
    })
  })
})

我可以在调用 new Date() 的示例中看到模拟日期,但测试未通过。我也试过:

export const nextYear = () => today.getFullYear() + 1

并尝试查看 new Date() returns 模拟值,但没有成功。

  1. 为什么 new Date() 调用没有在代码中被模拟,而在示例中却被模拟?
  2. 即使像这样的小计算,它也应该是函数而不是常量吗?

你基本上在做的是:

const today = new Date()
const nextYear = today.getFullYear() + 1
var MockDate = require("mockdate")
MockDate.set('2030-11-22')

console.log(nextYear)

您不能模拟已经实例化的日期。

解决方案可能是:

export const dynamicNextYear = () => (new Date()).getFullYear() + 1

此解决方案仅在调用函数时实例化日期,因此 MockDate 将能够模拟它。

或者您甚至可以在导入文件之前使用 MockDate(我不是足够的 js 专家来告诉您何时以及如何进行导入解析)。

我已经 runkit 到 fiddle 了