![](/img/trans.png)
[英]Javascript validation doesn't work when a wrong value entered before
[英]Testing props, doesn't fail when wrong type is entered
我正在使用 MERN 堆栈和 Redux。 我正在尝试在我的一个组件上测试我的一些道具。 我已经定义了所有类型并创建了一些测试,但即使我的测试输入了错误的数据类型,它们似乎也通过了。 任何人都知道我错过了什么。 我尝试添加每个 PropType 的形状,也尝试添加对象本身,但似乎都没有任何区别。
零件
Subject.propTypes = {
subjects: PropTypes.arrayOf(PropTypes.object).isRequired,
comments: PropTypes.arrayOf(PropTypes.object).isRequired,
users: PropTypes.arrayOf(PropTypes.object).isRequired,
newPost: PropTypes.object,
};
测试
describe("Checking PropTypes", () => {
it("Should not throw a warning", () => {
const expectedProps = {
subjects: [
{
title: "title test one",
Summary: "summary test one",
description: "description test one",
rating: 1,
noOfVotes: 1,
author: "author test one",
category: "category test one",
date: Date.now,
true: 1,
false: 1,
mostlyTrue: 1,
mostlyFalse: 1,
halfAndHalf: 1,
links: "links test one",
},
],
comments: [
{
title: "comments-title test one",
date: Date.now,
comment: "comments-comment test one",
author: 12345,
subject: 12345,
topic: "comments-topic test one",
rating: 1,
noOfVotes: 1,
},
],
users: [
{
name: "users-name test one",
email: "users-email test one",
password: "users-password test one",
date: Date.now,
rating: 1,
noOfVotes: 1,
},
],
newPost: {
title: "newPost-title test one",
date: Date.now,
comment: "newPost-comment test one",
author: "12345",
subject: "12345",
topic: "newPost-topic test one",
rating: 2,
noOfVotes: 2,
},
};
const propsErr = checkPropTypes(
Subject.propTypes,
expectedProps,
"props",
"Subject"
);
expect(propsErr).toBeUndefined();
});
所以即使这通过了
describe("Checking PropTypes", () => {
it("Should not throw a warning", () => {
const expectedProps = {
subjects: 22,
comments: 45,
users: 88,
newPost: 0,
};
const propsErr = checkPropTypes(
Subject.propTypes,
expectedProps,
"props",
"Subject"
);
expect(propsErr).toBeUndefined();
});
函数 checkPropTypes() 返回 void 因此 propsErr 将始终未定义。
一个解决方案可能是检查console.error不输出任何警告以使测试通过。
describe("Checking PropTypes", () => {
it("Should not throw a warning", () => {
const expectedProps = {
// your expected props
};
const consoleSpy = jest.spyOn(console, "error");
checkPropTypes(Subject.propTypes, expectedProps, "props", Subject.name);
expect(consoleSpy).not.toHaveBeenCalled();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.