因此,在测试组件抛出Jest环境时,我需要在function
内进行setInteval
回调。但是现在我总是在字符串an error message
上得到expect(setInterval).toHaveBeenLastCalledWith(expect.any(timer()), 20000)
:
预期的上次调用模拟函数: 未定义 作为参数1,但它被称为 [匿名功能]。
我真的不明白如何将我的函数_startPoolingTimer
从组件传递到toHaveBeenLastCalledWith
中的测试...
感谢您的帮助
测试文件:
import React from 'react'
import { shallow, mount } from 'enzyme'
import initialState, { attemptButtonActive } from './mocks/row'
import Row from '../Row'
describe('<Row />', () => {
it('timer should start, make pooling request and after 20000 mc make pool request again', () => {
jest.useFakeTimers()
const Component = mount(<Row {...initialState} />)
const { poollingTimerId, count } = Component.instance().state
const timer = Component.instance()._startPoolingTimer
expect(count).toBe(1)
expect(poollingTimerId).toBeTruthy()
expect(setInterval).toHaveBeenCalledTimes(1)
expect(setInterval).toHaveBeenLastCalledWith(expect.any(timer()), 20000)
expect(count).toBe(9)
})
})
组件文件:
import PropTypes from 'prop-types'
import React, { PureComponent } from 'react'
export class Row extends PureComponent {
constructor(props) {
super(props)
this.state = {
count: 0,
poollingTimerId: null
}
}
componentDidMount() {
let poollingTimerId = setInterval(this._startPoolingTimer, 20000)
}
_startPoolingTimer = () => {
const { startPooling, additionalInfoGlobal } = this.props
const moneyFromServer = additionalInfoGlobal.moneyToCollect
startPooling()
this.setState({
count: moneyFromServer
})
}
render() {
return (
<Row {...props}>
{'hh'}
</Row>
)
}
}
export default Row
答案 0 :(得分:0)
import PropTypes from 'prop-types'
import React, { PureComponent } from 'react'
import {connect} from 'react-redux';
export class Row4Collect extends PureComponent {
constructor(props) {
super(props)
this.state = {
count: 0,
poollingTimerId: null
}
}
componentDidMount() {
let poollingTimerId = setInterval(this.props._startPoolingTimer, 20000)
}
_startPoolingTimer = () => {
const { startPooling, additionalInfoGlobal } = this.props
const moneyFromServer = additionalInfoGlobal.moneyToCollect
startPooling()
this.setState({
count: moneyFromServer
})
}
render() {
return (
<Row {...props}>
{'hh'}
</Row>
)
}
}
const mapDispatchToProps = (dispatch) => {
return {
_startPoolingTimer: () => this._startPoolingTimer()
}
}
export default connect(undefined, mapDispatchToProps )(Row);
像这样更新它。
完成更新后,将间谍用作道具并测试功能。
您的测试看起来像这样
import React from 'react'
import { shallow, mount } from 'enzyme'
import Row from '../Row'
describe('<Row />', () => {
it('timer should start, make pooling request and after 20000 mc make pool request again', () => {
const spyFn = jest.fn();
const Component = mount(<Row {...initialState} _startPoolingTimer= {spyFn} />)
expect(spyFn).toHaveBeenLastCalledWith();
})
})
我已经开玩笑了。