开玩笑 - 从时刻时区模拟属性和函数



我试图使用笑话来模拟属性tz和函数,但我不知道一起模拟这两件事:

如果运行类似以下内容:

jest.mock('moment-timezone', () => () => ({weekday: () => 5}))
jest.mock('moment-timezone', () => {
return {
tz: {
}
}
})

我可以模拟属性tz或指令moment().如何编写模拟来覆盖此代码?

const moment = require('moment-timezone')
module.exports.send = () => {
const now = moment()
moment.tz.setDefault('America/Sao_Paulo')
return now.weekday()
}

谢谢

你可以利用第二个参数jest.mock(),这将允许您指定模拟模块的自定义实现以用于测试。

在此自定义实现中,您还可以定义一些方便的帮助程序来模拟预期的实现值(例如weekday()(。

// send-module.test.js
jest.mock('moment-timezone', () => {
let weekday
const moment = jest.fn(() => {
return {
weekday: jest.fn(() => weekday),
}
})
moment.tz = {
setDefault: jest.fn(),
}
// Helper for tests to set expected weekday value
moment.__setWeekday = (value) => weekday = value
return moment;
})
const sendModule = require('./send-module')
test('test', () => {
require('moment-timezone').__setWeekday(3)
expect(sendModule.send()).toBe(3)
})

请注意,如果被模拟的模块具有巨大的 API 图面,则手动为每个测试文件提供模拟可能会变得乏味和重复。为了解决后一种情况,您可以考虑编写一些手动模拟以使它们可重用(即使用__mocks__目录约定(并通过使用jest.genMockFromModule()来补充它。

Jest 文档对此有一些指导。

最新更新