如何测试React Number Format



我在这里使用了React Number Format包,我想测试它的onChange事件,但我遇到了一个错误,有人能帮我吗。我在下面给出了我的测试代码和组件。在代码的fireEevent方法中,它一直说"HTMLElement|null"类型的参数不可分配给"Element|Node|Document|Window"类型的参数

我的测试用例:

import React from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import LoanAmount from './LoanAmount'
import ReactDOM from 'react-dom';
import NumberFormat from 'react-number-format';

it("renders correctly", () => {
const { queryByPlaceholderText } = render(<LoanAmount/>)
expect(queryByPlaceholderText('Enter Loan Amount')).toBeTruthy
})
describe("input value", () => {
it("Updates on change", () => {
const {queryByPlaceholderText} = render(<LoanAmount/>)

const amountInput = queryByPlaceholderText("Enter Loan Amount")
fireEvent.change(amountInput, {target: {value: "4000"}})  //<--- shows error
expect(amountInput.value).toBe("4000") //<-- and here as well

})
})

我的React组件具有反应编号格式:

import React from 'react'
import styled from 'styled-components';
import NumberFormat from 'react-number-format';
import { useState } from 'react';
import { type } from 'os';
function LoanAmount() {
const [amount, setAmount] = useState("");
const [error, setError] = useState("");
const handleChnage = (e: { target: { value: string; }; }) => {
const loanAmount = e.target.value;
let number = Number(loanAmount.replace(/[^0-9.-]+/g,"")); //removes everything from the number except dot
//number = Math.round(number);
setAmount(number.toString());
number < 4000 || number > 100000 ? setError("Your total loan amount must be between $4,000 and $100,000") : setError("");
}
const inputs = document.querySelectorAll('NumberFormat');
console.log(inputs.length);
return (
<LoanAmountContainer>
<LoanAmountForm>
<label>Loan Amount</label>
<span> 
<NumberFormat
className="loanAmount"
name="amount"
thousandSeparator={true}
decimalScale={2}
fixedDecimalScale={true}
prefix="$"
value={amount}
onChange={handleChnage}
placeholder="Enter Loan Amount"
/>
</span>
<small>{error}</small>
</LoanAmountForm>
</LoanAmountContainer>
)
}
export default LoanAmount
const LoanAmountContainer = styled.div`
`
const LoanAmountForm = styled.div`
`

尝试使用RegExp来匹配HTML元素,并在screen实例上调用queryByPlaceholderText

describe('input value', () => {
it('Updates on change', () => {
render(<LoanAmount />);
const amountInput = screen.queryByPlaceholderText(/Enter Loan Amount/i);
fireEvent.change(amountInput, { target: { value: '4000' } }); 
expect(amountInput.value).toBe('4000'); 
});
});

最新更新