我想使用Luxon测试以下内容:
import { DateTime } from 'luxon'
export const calculateAge = (birthDate: DateTime) => {
let dateDifference = Math.abs(birthDate.diffNow('years').years)
if (dateDifference < 1) {
dateDifference = Math.abs(birthDate.diffNow('months').months)
}
return String(Math.floor(dateDifference))
}我刚开始使用React Native并使用Jest进行测试,但到目前为止,我测试的'it‘块看起来像这样:
it('calls the calculates age function', () => {
jest.spyOn(calculateAge, calculateAge('1950-02-02'))
expect(calculateAge).toHaveBeenCalled()
})我得到以下错误:
TypeError: birthDate.diffNow is not a function
有人知道我怎么测试这个吗?
发布于 2021-08-08 08:36:06
您通常只需要监视传递的回调,以检查它们是否被实际调用。在这里,您正在测试一个函数,因此您肯定不想模拟或监视它。
export const calculateAge = (birthDate: DateTime) => {
let dateDifference = Math.abs(birthDate.diffNow('years').years)
if (dateDifference < 1) {
dateDifference = Math.abs(birthDate.diffNow('months').months)
}
return String(Math.floor(dateDifference))
}关于TypeError: birthDate.diffNow is not a function错误,这是因为calculateAge需要一个Luxon DateTime对象,而您正在传递一个String对象。
对于测试,您需要模拟javascript日期/时间,以便可以可靠地与测试中的静态日期进行比较,否则每次测试运行时,now时间总是不同的。
import { advanceTo, clear } from 'jest-date-mock';
...
afterAll(() => {
clear(); // clear jest date mock
});
it('should compute diff in years', () => {
// Set "now" time
advanceTo(DateTime.fromISO('2021-08-08T01:20:13-0700').toJSDate());
expect(calculateAge(DateTime.fromISO('2020-08-07T00:00:00-0700'))).toEqual('1');
});
it('should compute diff in months', () => {
// Set "now" time
advanceTo(DateTime.fromISO('2021-08-08T01:20:13-0700').toJSDate());
expect(calculateAge(DateTime.fromISO('2020-08-09T00:00:00-0700'))).toEqual('11');
});您可以想到其他有趣的测试/边界情况。
https://stackoverflow.com/questions/68698633
复制相似问题