如何使用Jest测试输出是随机的函数?像这样:
import cuid from 'cuid';
const functionToTest = (value) => ({
[cuid()]: {
a: Math.random(),
b: new Date().toString(),
c: value,
}
});
Run Code Online (Sandbox Code Playgroud)
所以输出functionToTest('Some predictable value')将是这样的:
{
'cixrchnp60000vhidc9qvd10p': {
a: 0.08715126430943698,
b: 'Tue Jan 10 2017 15:20:58 GMT+0200 (EET)',
c: 'Some predictable value'
},
}
Run Code Online (Sandbox Code Playgroud) 我试图模拟new Date()返回一个特定的日期。以下代码:
const now = new Date()
jest.spyOn(global, 'Date').mockImplementation(() => now)
Run Code Online (Sandbox Code Playgroud)
给出一个编译错误:Argument of type '() => Date' is not assignable to parameter of type '() => string'. Type 'Date' is not assignable to type 'string'。
我认为原因是 jest 认为我正在尝试模拟Date()而不是new Date(). 确实,Date()返回一个字符串。我该如何解决这个问题?