测试道具,输入错误类型不会失败



我使用的是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将始终未定义。

一个解决方案可以是检查控制台.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();
});

相关内容

  • 没有找到相关文章

最新更新