我正在用来testing-library测试单选按钮组的实现。我可以测试将tab焦点设置到第一个单选选项,但我无法正确测试箭头键导航。
这是我的测试:
import {
getByLabelText,
render,
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
...
test('arrow key navigation', () => {
const {container} = render(
<div>
<label htmlFor="apple">
Apple
<input type="radio" value="apple" id="apple" name="fruit"/>
</label>
<label htmlFor="banana">
Banana
<input type="radio" value="banana" id="banana" name="fruit"/>
</label>
</div>
)
const apple = getByLabelText(container, 'Apple')
const banana = getByLabelText(container, 'Banana')
userEvent.tab()
expect(apple).toHaveFocus() // This assertion passes
userEvent.keyboard('{arrowright}')
expect(banana).toHaveFocus() // This assertion fails
})
Run Code Online (Sandbox Code Playgroud) 我有一个例子,我经常一起检查布尔值和另一个联合类型的值。虽然它们在逻辑上是相连的,并且假设可以只检查其中之一,但我需要检查两者,以便 TS 编译器知道这两种类型。
let multiple: boolean
let value: Array<string> | string
...
if (multiple && isArray(value)) {
// TS knows multiple === true and value is an Array
}
Run Code Online (Sandbox Code Playgroud)
有没有办法编写类型检查函数,其中类型谓词断言多个值?
像这样的东西:
// Not valid Typescript
function isMulti (
multi: boolean,
value: Array<string> | string
): (multi is true) && (value is Array<string>) {
return multi && isArray(value)
}
Run Code Online (Sandbox Code Playgroud)
在大多数情况下,我只需检查即可isArray,但有些情况下我想重复使用上面的检查。这可能吗?
回复@kaya3:
为了给出更准确的用例,我有类似以下内容:
我可以将multiple和分配value给具有 DiscriminatedUnion 类型的对象,但这会增加比我认为需要的更多的复杂性。
type ValueType<M extends boolean> = M extends true ? Array<string> …Run Code Online (Sandbox Code Playgroud) 我有一个 React 应用程序,我在其中隐藏/显示基于状态的元素,并希望在状态变量更改后对该 DOM 元素进行一些计算。
我尝试过使用useLayoutEffect,但这仍然在DOM 更新之前运行,所以我的计算没有用。我的理解是useLayoutEffect错了?是我使用方式不对吗?
这是我所拥有的
const myComponent = () => {
const elem = useRef()
const [isElemVisible, setIElemVisible] = useState(false)
useLayoutEffect(() => {
// I want this to run AFTER the element is added/removed from the DOM
// Instead this is run before the element is actually modified in the DOM (but the ref itself has changed)
elem.current.getBoundingClientRect() // do something with this object if it exists
}, [elem.current])
return ( …Run Code Online (Sandbox Code Playgroud)