記事を書こうと考えた背景について
入力フォームに入力ができるかをテストする際に、
findByLabelTextを要素の取得を行うときに使用していました。
findByLabelTextだとラベル名が今後変ってしまう可能性があるため、data-testidの方が良いといただいたので、変更しようと思いました。
しかし、複数のフォームでそれぞれにdata-testidを付与して要素を特定するにはどのようにしたらよいのかを迷ってしまったのでまとめておこうと考えました。
元のコード
画面側
App.jsx
<InputForm
name="content"
value={inputs.content}
onChange={handleInputChange}
label="学習内容"
id="learnContent"
/>
<InputForm
name="time"
value={inputs.time}
onChange={handleInputChange}
label="学習時間"
id="learnTime"
suffix="時間"
pattern="^[0-9]*$"
/>
コンポーネント側
InputForm.jsx
export const InputForm = (props) =>{
const {name,value, onChange, label,id,suffix,pattern}=props;
return(
<>
<label htmlFor={id}>{label}</label>
<input id={id} name={name} value={value} onChange={onChange} pattern={pattern} />
<span>{suffix}</span>
</>
);
};
テストコード
componenteSample.spec.jsx
describe("フォームに入力ができること", () => {
test("学習内容が入力できる",
async () => {
const learnRecordForm = await screen.findByLabelText("学習内容");
fireEvent.change(learnRecordForm, {target: { value: "test" }});
expect(learnRecordForm).toHaveValue("test");
}
);
});
describe("フォームに入力ができること", () => {
test("学習時間が入力できる",
async () => {
const learnTimeRecordForm = await screen.findByLabelText("学習時間");
fireEvent.change(learnTimeRecordForm, {target: { value: 12 }});
//入力した値を数値に変換して入力値と等しいかを比較する。
expect(Number(learnTimeRecordForm.value)).toBe(12);
}
);
});
行ったこと
-
入力フォーム(画面側の表示をしているファイル)でプロパティとしてidを使用し、コンポーネント側にpropsとしてidを渡します。
コンポーネント側でpropsを受け取り、受け取ったidをdata-testidを使用して、どちらの入力フォームであるかを特定できるように定義しました。 -
findByLabelTextではなく、findByTestIdで要素の取得をするように変更しました。
修正したコード
画面側
特に変更していないので元のコードと同じです。
コンポーネント側
InputForm.jsx
export const InputForm = (props) =>{
const {name,value, onChange, label,id,suffix,pattern}=props;
return(
<>
<label htmlFor={id}>{label}</label>
<input id={id} name={name} value={value} onChange={onChange} pattern={pattern} data-testid={id} />
<span>{suffix}</span>
</>
);
};
テストコード
componenteSample.spec.jsx
describe("フォームに入力ができること", () => {
test("学習内容が入力できる",
async () => {
const learnRecordForm = await screen.findByTestId("learnContent");
fireEvent.change(learnRecordForm, {target: { value: "test" }});
expect(learnRecordForm).toHaveValue("test");
screen.debug(learnRecordForm);
}
);
});
describe("フォームに入力ができること", () => {
test("学習時間が入力できる",
async () => {
const learnTimeRecordForm = await screen.findByTestId("learnTime");
fireEvent.change(learnTimeRecordForm, {target: { value: 12 }});
//入力した値を数値に変換して入力値と等しいかを比較する。
expect(Number(learnTimeRecordForm.value)).toBe(12);
screen.debug(learnTimeRecordForm);
}
);
});