reactjs - 使用 JEST 在 ReactJS 单元测试中期望返回 HTML
问题描述
我正在尝试对该功能进行单元测试
export const scoreText = score => {
if (score < 1.0) {
return <span style={{ color: '#fd7878' }}>{score}</span>;
}
if (score >= 1.0 && score <= 1.5) {
return <span style={{ color: '#fd7878' }}>{score}</span>;
}
if ((score >= 1.51 && score <= 2.49) || (score >= 2.5 && score <= 3.0)) {
return <span style={{ color: '#2fcc71' }}>{score}</span>;
}
return score;
};
这是我现在的代码。如何进行单元测试以期望返回 HTML 代码?
describe('scoreText', () => {
it('score less than 1.0', () => {
expect(scoreText(0).toBeLessThan(1.0));
});
it('score not less than or equal to 1.0 greater than or equal to 1.5', () => {
expect(scoreText(1.2).toBeLessThanOrEqual(1.5));
});
it('score not less than or equal to 1.5 greater than or equal to 2.49', () => {
expect(scoreText(2.0).toBeLessThanOrEqual(2.49));
});
});
解决方案
就想看到整个html
返回而言,我认为你应该去使用snapshot
测试。
toMatchSnapshot()
通常,您会生成 html 内容并存储为文件,您可以使用api检查它是否正确:
it('score less than 1.0', () => {
expect(scoreText(0)).toMatchSnapshot();
});
然后您会看到快照如下所示:
exports[`scoreText score less than 1.0 1`] = `
<span
style={
Object {
"color": "#fd7878",
}
}
>
0
</span>
`;
推荐阅读
- reporting-services - 如果我们需要考虑两个参数,如何在 SSRS 中定义行数据组?
- asp.net - ASP.NET CORE 应用程序在启动页面上显示 index.html 页面,尽管我没有任何中间件
- reactjs - ant design 清除所有复选框
- java - 并发哈希图删除复杂值
- r - R 旋转包含向量的数据框单元格
- javascript - 如何在Javascript中打印一次日期标签
- android - Intellij 2019 2.3 插件 Andriod 支持中的异常
- python - 日期时间转换 ValueError Pandas
- hyperledger-fabric - 使用 vscode 在 ibm 区块链平台中运行 invoke.js 时出错?
- c - C 究竟在哪些情况下会引发分段错误?