gpt4 book ai didi

javascript - Jest - React 组件中的模拟粗箭头功能

转载 作者:数据小太阳 更新时间:2023-10-29 05:35:01 25 4
gpt4 key购买 nike

鉴于我的组件和下面的测试,为什么我的 confirmClickHandler 方法在我运行测试时仍然被调用?

注意:我注意到,当我将方法从粗箭头函数更改为常规函数时,它会被正确地模拟出来。我在这里缺少什么?

class CalendarConfirmation extends React.Component {
...

confirmClickHandler = (e) => {
...
}
}

和我的测试:

import React from 'react';
import {mount} from 'enzyme';
import CalendarConfirmation from '../components/CalendarConfirmation';

describe('Test CalendarConfirmation', () => {
let calendarConfirmation;
calendarConfirmation = mount (<CalendarConfirmation />);
calendarConfirmation.instance().confirmClickHandler = jest.fn();
...
}

最佳答案

这对我有用:

import React from 'react'
import { mount, shallow } from 'enzyme'

class Foo extends React.Component {
// babel transpiles this too Foo.prototype.canMock
protoMethod () {
// will be mocked
}

// this becomes an instance property
instanceMethod = () => {
return 'NOT be mocked'
}

render () {
return (<div>{`${this.protoMethod()} ${this.instanceMethod()}`}</div>)
}
}

Foo.prototype.protoMethod = jest.fn().mockReturnValue('you shall')

it('should be mocked', () => {
const mock = jest.fn().mockReturnValue('be mocked')
const wrapper = mount(<Foo />)
wrapper.instance().instanceMethod = mock
wrapper.update()
expect(mock).toHaveBeenCalled()
})

但是请注意,当使用 shallow 而不是 mount 时,这会失败。

关于javascript - Jest - React 组件中的模拟粗箭头功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45511175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com