Unit testing 开玩笑的模仿文件
我在react应用程序服务中使用了以下方法,需要进行单元测试Unit testing 开玩笑的模仿文件,unit-testing,jestjs,Unit Testing,Jestjs,我在react应用程序服务中使用了以下方法,需要进行单元测试 onDeclineCallback = () => { console.log("boom " + document.referrer); if (document.referrer === "") { console.log("redirect to our age policy page"); } else { history.back(); } }; 我的单元
onDeclineCallback = () => {
console.log("boom " + document.referrer);
if (document.referrer === "") {
console.log("redirect to our age policy page");
} else {
history.back();
}
};
我的单元测试当前看起来像:
history.back=jest.fn();//嘲弄历史。回到笑话fn
描述('年龄验证服务测试',()=>{
它('如果被拒绝且推荐人可用,则将用户返回给推荐人',()=>{
文件={
…文件,
referer:'Refferer Test',//我模仿整个文档对象的恶意尝试
};
ageVerification.onDeclineCallback();
期望(历史。返回)。已被调用的时间(1);
});
});
我试图找到一种模仿document.referer的方法,以便为每个案例编写一个单元测试。任何人都可以为此提供方法吗?您可以使用
对象.defineProperty
方法设置文档.referer的模拟值
例如。
index.ts
:
导出类验证{
公共onDeclineCallback=()=>{
console.log('boom'+文件引用方);
如果(document.referer==''){
log('重定向到我们的年龄策略页面');
}否则{
历史。返回();
}
};
}
索引规范ts
:
从“/”导入{AgeVerification};
描述('年龄验证服务测试',()=>{
让我们来验证一下;
在每个之前(()=>{
ageVerification=新的ageVerification();
history.back=jest.fn();
});
毕竟(()=>{
开玩笑。恢复记忆();
jest.resetAllMocks();
});
它('如果被拒绝且推荐人可用,则将用户返回给推荐人',()=>{
const originalreferer=document.referer;
defineProperty(文档'referer',{value:'referer Test',可配置:true});
ageVerification.onDeclineCallback();
期望(历史。返回)。已被调用的时间(1);
defineProperty(文档'referer',{value:originalreferer});
});
它('应该打印日志',()=>{
constlogspy=jest.spyOn(控制台,'log');
ageVerification.onDeclineCallback();
expect(logSpy.mock.calls[0]).toEqual(['boom']);
expect(logSpy.mock.calls[1]).toEqual(['redirect to our age policy page']);
});
});
100%覆盖率的单元测试结果:
通过src/stackoverflow/59198002/index.test.ts(13.915s)
年龄验证服务测试
✓ 如果被拒绝且推荐人可用,则将用户返回给推荐人(17ms)
✓ 应打印日志(3ms)
console.log src/stackoverflow/59198002/index.ts:264
动臂反射试验
console.log node_modules/jest mock/build/index.js:860
繁荣
console.log node_modules/jest mock/build/index.js:860
重定向到我们的年龄政策页面
----------|----------|----------|----------|----------|-------------------|
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s|
----------|----------|----------|----------|----------|-------------------|
所有文件| 100 | 100 | 100 | 100 ||
index.ts | 100 | 100 | 100 | 100 ||
----------|----------|----------|----------|----------|-------------------|
测试套件:1个通过,共1个
测试:2次通过,共2次
快照:共0个
时间:15.385s
源代码: