![](/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.