Я пытаюсь проверить, что функция вызывается в ловушке componentDidMount
. Я пробовал два подхода к spyOn, но ни один из них не работает. Что я делаю не так?
MyTest. js
import { shallow } from 'enzyme'
import { Provider } from 'react-redux'
import configureStore from 'redux-mock-store'
import MyComponent from 'MyComponent'
const mockStore = configureStore([])
describe('<MyComponent />', () => {
let store
beforeEach(() => {
store = mockStore({
foo: 'bar'
})
})
afterEach(() => {
spy.mockClear()
})
Подход 1:
Это дает ошибка
TypeError: Cannot read property 'myFunction' of null
it("function is called onMount", () => {
const wrapper = shallow(
<Provider store={store}>
<MyComponent myProp={prop}/>
</Provider>
)
spy = jest.spyOn(wrapper.instance(), 'myFunction')
expect(spy).toHaveBeenCalledTimes(1)
})
Подход 2:
Это дает ошибку:
Cannot spyOn on a primitive value; undefined given
it("function is called onMount", () => {
spy = jest.spyOn(MyComponent.prototype, 'myFunction')
const wrapper = shallow(
<Provider store={store}>
<MyComponent myProp={prop}/>
</Provider>
)
expect(spy).toHaveBeenCalledTimes(1)
})
})
MyComponent.jsx
class MyComponent extends Component {
constructor() {
super();
}
componentDidMount() {
this.myFunction()
}
async myFunction() {}
render(){
return(<div></div>)
}
}
function mapStateToProps(state) {
return {
foo: state.foo
}
}
export default connect(mapStateToProps)(MyComponent)