입력을 테스트하고 있습니다.효소의 초점()
테스트 방법input.focus()
효소의저는 리액션으로 대본을 쓰고 있습니다.내 코드는 다음과 같습니다.
public inputBox: any;
componentDidUpdate = () => {
setTimeout(() => {
this.inputBox.focus();
}, 200);
}
render() {
return (
<div>
<input
type = 'number'
ref = {element => this.inputBox = element } />
</div>
);
}
사용할 수 있습니다.mount
천박한 대신에그러면 당신은 비교할 수 있습니다.document.activeElement
입력 DOM 노드를 사용합니다.
const output = mount(<MyFocusingComponent/>);
assert(output.find('input').node === document.activeElement);
자세한 내용은 https://github.com/airbnb/enzyme/issues/316 을 참조하십시오.
Per React 16.3 업데이트...만약 당신이 새로운 refapi를 사용하기 위해 원래 구성요소를 재정렬한다면, 오늘 이 게시물을 방문하는 모든 사람을 위해 사용합니다.
class InputBox extends PureComponent {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
componentDidMount() {
this.inputRef.current.focus();
}
render() {
return (
<input
ref={this.inputRef}
/>
);
}
}
그런 다음 테스트 사양에서
it("Gives immediate focus on to name field on load", () => {
const wrapper = mount(<InputBox />);
const { inputRef } = wrapper.instance();
jest.spyOn(inputRef.current, "focus");
wrapper.instance().componentDidMount();
expect(inputRef.current.focus).toHaveBeenCalledTimes(1);
});
의 사용에 주의하십시오.inputRef.current
현재 할당된 DOM 노드를 참조하는 속성입니다.
다른 접근법은 요소가 초점을 얻는지 테스트하는 것입니다.focus()
노드 요소에서 호출됩니다.이를 위해 초점을 맞춘 요소는 다음을 통해 참조되어야 합니다.ref
예에서 발생하는 것과 같은 태그 - 참조가 다음에 할당되었습니다.this.inputBox
아래의 예를 고려해 보십시오.
const wrapper = mount(<FocusingInput />);
const element = wrapper.instance().inputBox; // This is your input ref
spyOn(element, 'focus');
wrapper.simulate('mouseEnter', eventStub());
setTimeout(() => expect(element.focus).toHaveBeenCalled(), 250);
이 예에서는 Jasmine의 SpyOn을 사용하지만 원하는 모든 스파이를 사용할 수 있습니다.
저도 같은 문제가 있었고 다음과 같은 접근 방식을 사용하여 해결했습니다.
내 설정은 Jest(반응-생성-앱) + Enzy:
it('should set the focus after render', () => {
// If you don't create this element you can not access the
// document.activeElement or simply returns <body/>
document.body.innerHTML = '<div></div>'
// You have to tell Enzyme to attach the component to this
// newly created element
wrapper = mount(<MyTextFieldComponent />, {
attachTo: document.getElementsByName('div')[0]
})
// In my case was easy to compare using id
// than using the whole element
expect(wrapper.find('input').props().id).toEqual(
document.activeElement.id
)
})
이것은 사용할 때 효과가 있었습니다.mount
그리고.useRef
후크:
expect(wrapper.find('input').get(0).ref.current).toEqual(document.activeElement)
선택기를 사용하여 특정 요소에 대한 포커스를 확인할 수 있습니다.
const wrapper = mount(<MyComponent />);
const input = wrapper.find('input');
expect(input.is(':focus')).toBe(true);
선택 기준data-test
속성이나 비슷한 것이 제가 생각할 수 있는 가장 직접적인 해결책이었습니다.
import React, { Component } from 'react'
import { mount } from 'enzyme'
class MyComponent extends Component {
componentDidMount() {
if (this.inputRef) {
this.inputRef.focus()
}
}
render() {
return (
<input data-test="my-data-test" ref={input => { this.inputRef = input } } />
)
}
}
it('should set focus on mount', () => {
mount(<MyComponent />)
expect(document.activeElement.dataset.test).toBe('my-data-test')
})
이것은 효과가 있을 것입니다.
const wrapper = mount(<MyComponent />);
const input = wrapper.find('input');
expect(input).toHaveFocus();
언급URL : https://stackoverflow.com/questions/37694900/testing-input-focus-in-enzyme
'programing' 카테고리의 다른 글
Firebase에서 배열 유형 문서 항목에 타임스탬프를 할당하는 방법 (0) | 2023.06.08 |
---|---|
pyproject.toml 파일은 무엇을 위한 것입니까? (0) | 2023.06.08 |
안드로이드:onClick XML 속성은 setOnClickListener와 정확히 어떻게 다릅니까? (0) | 2023.06.08 |
행렬도:lib getylim 값 (0) | 2023.06.08 |
wordpress 포스트 유효성 검사 추가 (0) | 2023.06.08 |