警告:我对Jest很陌生,所以小熊。
我正在尝试使用名为DateFilter的Jest测试Vue2.js过滤器。此筛选器只对传递给它的日期应用日期格式。
DateFilter.js
import Vue from 'vue';
import moment from 'moment';
const dateFormatter = (dateValue, dateFormat) => {
return moment(dateValue).format(dateFormat);
};
Vue.filter('date', dateFormatter);
export default dateFormatter;所以,我在这里看到了三个有效的单元测试
DateFilter.test.js
import moment from 'moment';
import DateFilter from './DateFilter';
describe('DateFilter', () => {
it('should exist', () => {
expect(DateFilter).toBeDefined();
expect(typeof DateFilter).toBe('function');
});
it('should moment.format with the dateValue and dateFormat passed.', () => {
// Here I get lost in how to spyOn moment function and the .format function
const mockDateFormat = `dateFormat-${Math.random()}`;
const mockDate = `mockDate-${Math.random()}`;
jest.mock('moment', () => {
return { format: jest.fn() }
});
// expect moment to have been called with mockDate
// expect moment(mockDate) to have been called with mockDateFormat
});
});发布于 2018-07-26 08:28:35
不知道你想测试什么细节,但我猜秘密是对瞬间的一个很好的嘲弄。由于您只想测试您的dateFormatter,所以可以执行以下操作:
首先,我们将模拟设置为小游戏:
jest.mock('moment', () => {
const momentMock = { format: jest.fn() }
return jest.fn(() => momentMock);
});如果您没有声明const,而是尝试将对象传递给jest.fn,您可能会得到函数没有被调用的错误,这是因为我们每次调用时都会生成不同的模拟,而不是对所有moment调用使用相同的模拟。
这是一个非常简单的例子,您可以做一个更详细的瞬间模拟,但我认为不值得这么做,因为您的功能已经足够简单了。
然后,我认为您已经分离了单元测试,您可以在一次测试中使用它们,但有时最好分别断言功能链。
it('calls moment with the dateValue passed.', () => {
const mockDateFormat = `dateFormat-${Math.random()}`;
const mockDate = `mockDate-${Math.random()}`;
dateFormatter(mockDate, mockDateFormat);
expect(moment).toHaveBeenCalledWith(mockDate)
});
it('calls format with the dateFormat passed.', () => {
const mockDateFormat = `dateFormat-${Math.random()}`;
const mockDate = `mockDate-${Math.random()}`;
dateFormatter(mockDate, mockDateFormat);
expect(moment(mockDate).format).toHaveBeenCalledWith(mockDateFormat)
});免责声明:在第二个测试中,您是否期望moment(), moment(mockDate) or moment('Whatever')并不重要,因为您总是模仿相同的东西,您将收到相同的format模拟返回。
如果您想要更复杂的东西,您将需要创建一个夹具,其中您需要将调用动量的日期映射到一个包含模拟函数的新对象。但我相信这是一个更多的麻烦,它实际上是更好的测试,这一刻已经被调用和格式已经被调用。否则,您将测试第三方库的工作方式。
希望这能给你一些指导
https://stackoverflow.com/questions/50956080
复制相似问题