Javascript 我如何测试一个潜在的不连续反应?
我最近决定开始为我所参与的一个项目编写测试,我们有一个React组件,我很难弄清楚如何正确地进行测试 该组件称为Javascript 我如何测试一个潜在的不连续反应?,javascript,unit-testing,testing,reactjs,chai,Javascript,Unit Testing,Testing,Reactjs,Chai,我最近决定开始为我所参与的一个项目编写测试,我们有一个React组件,我很难弄清楚如何正确地进行测试 该组件称为FallbackedImage,它获取字符串或字符串数组并呈现第一个有效图像,正如您可能理解的,这是一个异步操作 我想测试一下,如果提供了一个有效的字符串,它实际上是否渲染了一个图像,但我不能只运行它 it("renders img if src is valid string", () => { const wrapper = mount(<FallbackedIma
FallbackedImage
,它获取字符串或字符串数组并呈现第一个有效图像,正如您可能理解的,这是一个异步操作
我想测试一下,如果提供了一个有效的字符串,它实际上是否渲染了一个图像,但我不能只运行它
it("renders img if src is valid string", () => {
const wrapper = mount(<FallbackedImage src={validLink} />)
expect(wrapper.find("img")).to.have.length(1)
})
使用组件的onLoad
prop
这假设onLoad
-功能按预期工作,但感觉不正确,因为这不在本特定测试的范围内
it("renders img if src is valid string", done => {
const onLoad = () => {
expect(wrapper.find("img")).to.have.length(1)
done()
}
const wrapper = mount(
<FallbackedImage
onLoad={onLoad}
src={validLink} />
)
})
我真的认为你所做的是正确的。应该没有问题。使用
onLoad
-prop?我不认为这是正确的,因为如果组件没有该功能,我将如何测试它?实际上,为什么onLoad
prop存在问题?我不认为这是一个问题。这也是为什么将接口隔离原则作为软件开发规程使用一点问题都没有的原因;它允许通过模拟进行更简单的测试。再说一遍,onLoad
prop甚至存在什么实际问题?
it("renders img if src is valid string", done => {
const onLoad = () => {
expect(wrapper.find("img")).to.have.length(1)
done()
}
const wrapper = mount(
<FallbackedImage
onLoad={onLoad}
src={validLink} />
)
})
import React, { Component, PropTypes } from "react"
import { noop } from "../../utils"
export default class FallbackedImage extends Component {
constructor(props) {
super(props)
this.componentDidMount = this.tryImage.bind(this)
this.testImg = new window.Image()
this.testImg.onerror = this.onError.bind(this)
this.testImg.onload = this.onLoad.bind(this)
this.photos = [].concat(props.src) // Make array from props.src if it's not
this.state = { index: 0 }
}
static propTypes = {
className: PropTypes.string,
onLoad: PropTypes.func,
src: PropTypes.oneOfType([
PropTypes.array,
PropTypes.string,
]),
}
static defaultProps = {
onLoad: noop,
}
onError() {
const nextIndex = this.state.index + 1
if (nextIndex <= this.photos.length) {
this.setState({ index: nextIndex }, this.tryImage)
}
}
onLoad() {
const { src } = this.testImg
this.setState({ src })
this.props.onLoad(src)
}
tryImage() {
this.testImg.src = this.photos[this.state.index]
}
shouldComponentUpdate(_nextProps, nextState) {
return !!nextState.src
}
render() {
const { src } = this.state
return src
? <img src={src} className={this.props.className} />
: null
}
}