Pal*_*tro 4 javascript reactjs jestjs enzyme chai-enzyme
我在使用新React.create()api的地方有一个组件,如何测试document.activeElement应该等于当前的ref组件。
零件 :
export class Automatic extends Component {
componentDidMount = () => this.focusContainer()
componentDidUpdate = () => this.focusContainer()
container = React.createRef()
focusContainer = () => this.container.current.focus()
render = () => {
return (
<div
name='automatic'
onKeyPress={this.captureInput}
onBlur={() => setTimeout(() => this.focusContainer(), 0) }
ref={this.container}
tabIndex={0}
>
.....
</div>
}
Run Code Online (Sandbox Code Playgroud)
旧测试(有效):
it('should focus container on mount', () => {
automatic = mount(<Automatic classes={{}} />, mountContext)
document.activeElement.should.be.equal(automatic.ref('container'))
})
Run Code Online (Sandbox Code Playgroud)
新的(无效):
it.only('should focus container on mount', () => {
const container = React.createRef()
automatic = mount(<Automatic classes={{}} />, mountContext)
document.activeElement.should.be.equal(automatic.ref(container.current))
})
Run Code Online (Sandbox Code Playgroud)
更新了工作示例。添加了样式组件示例。
这是我用Jest解决的方法(使用不同的断言,但概念相同):
// setup
const MyComponent = React.forwardRef((props, ref) => (
<div>
<span ref={ref}>some element</span>
</div>
))
// test
it('should contain the forwarded ref in the child span', () => {
const ref = React.createRef()
const component = mount(
<Fragment>
<MyComponent ref={ref} />
</Fragment>,
)
expect(component.find('span').instance()).toEqual(ref.current)
})
Run Code Online (Sandbox Code Playgroud)
ref。MyComponent在另一个元素中才起作用Fragment。使用**样式化组件时遇到了一些麻烦。这是因为它创建了许多额外的元素。尝试使用调试console.log(component.debug())。它会告诉你酶的作用。
调试时,您会看到Styled-Components使用推荐的方式转发道具。
您可以使用以下属性选择器找到合适的元素forwardedRef:
// setup
const El = styled.div`
color: red;
`
El.displayName = 'El'
const MyComponentWithStyledChild = React.forwardRef((props, ref) => (
<El ref={ref}>some element</El>
))
// test
it('should contain the forwarded ref in a rendered styled-component', () => {
const ref = React.createRef()
const component = mount(
<Fragment>
<MyComponentWithStyledChild ref={ref} />
</Fragment>,
)
// Styled-components sets prop `forwardedRef`
const target = component
.find('[forwardedRef]')
.childAt(0)
.instance()
expect(target).toEqual(ref.current)
})
Run Code Online (Sandbox Code Playgroud)
refit('should focus container on mount', () => {
automatic = mount(<Automatic classes={{}} />, mountContext)
document.activeElement.should.be.equal(automatic.instance().container.current)
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4794 次 |
| 最近记录: |