【发布时间】:2021-12-31 21:34:46
【问题描述】:
我目前正在学习 cypress.io,我有 7 checkboxes 代表一周中的每一天 Sun-Sat。
{days.map((day, idx) => (
<input
onChange={(e) => {
const { checked, value } = e.target;
setDays(
days => days.map(data => {
if (data.id === day.id) {
return {
...data,
id: value,
select: !data.select,
};
}
return data;
})
);
setDayId(prev => {
return checked
? [...prev, value] // add if checked
: prev.filter(val => val !== value) // remove if not checked
});
console.log("CHECKING CHECKED VALUE", e.target.checked);
// console.log("WHAT IS THE SET VALUE", values)
}}
key={idx}
name={day?.name}
type="checkbox"
value={day?.id}
checked={day.select}
id="habit-frequency"
/>
))}
我尽量避免这样做 7 次,因为我确信有更好的方法来做到这一点
cy.get("#habit-frequency")
.should("have.attr", "name", "Sun")
.should("have.attr", "value", "1");
我想这样做:
const DAYS = [
{ id: 1, name: "Sun", select: false },
{ id: 2, name: "Mon", select: false },
{ id: 3, name: "Tue", select: false },
{ id: 4, name: "Wed", select: false },
{ id: 5, name: "Thu", select: false },
{ id: 6, name: "Fri", select: false },
{ id: 7, name: "Sat", select: false },
];
DAYS.map(day => (
it(`Should have a checkbox for ${day.name}`, () => {
cy.get("#habit-frequency")
.should("have.attr", "name", day.name)
.should("have.attr", "value", day.id)
})
))
但它并没有真正起作用。有什么建议吗?这是我到目前为止编写的完整测试,以防万一
describe("Create Habit", () => {
beforeEach(() => {
cy.visit("/");
});
it("Should have a 'Habit' button which can be clicked to display a modal", () => {
cy.get("#modal-btn").should("contain", "Habit").click();
cy.get(".modal-title").should("contain", "Add Habit");
});
it("Should have a 'Add Habit' title, 2 inputs, one for name and one for description, a habit type option, a weekly frequency and an option to choose colors", () => {
cy.get("#modal-btn").click();
cy.get(".modal-title").should("contain", "Add Habit");
cy.get("#habit-name")
.should("have.attr", "placeholder", "Habit name");
cy.get("#habit-description")
.should("have.attr", "placeholder", "Habit description");
cy.get("#habit-todo")
.should("have.attr", "name", "To-Do")
.should("have.attr", "value", "1");
cy.get("#habit-nottodo")
.should("have.attr", "name", "Not-To-Do")
.should("have.attr", "value", "2");
DAYS.map(day => (
it(`Should have a checkbox for ${day.name}`, () => {
cy.get("#habit-frequency")
.should("have.attr", "name", day.name)
.should("have.attr", "value", day.id)
})
))
cy.get("#habit-frequency")
.should("have.attr", "name", "Sun")
.should("have.attr", "value", "1");
});
});
【问题讨论】: