我的代码的简化设置如下:
App.js
class App extends React.Component {
componentDidMount() {
const { thirdPartyAPI } = this.props;
thirdPartyAPI.field.onValueChanged(this.handleValueChange);
}
handleValueChange = (value) => {
// callback to do complex validation stuff and suchlike
// update state
}
render() {
// display stuff
}
}
App.test.js
each([...]).
.test('App is rendered according to...',
async (...) => {
const mockApi = {
field: {
onValueChanged: ????
}
}
const AppComponent = await shallow(
<App thirdPartyAPI={mockApi} />,
);
});
OnValueChanged 检测用户何时在 react-app 之外更改了值。从用户的 Angular 来看,这是可行的,但 Jest 测试给我带来了麻烦。
简单地说:我该如何测试它?
我需要模拟 API 函数,但我需要使用 App.js 中定义的回调函数 handleValueChange。我已经忘记了我读过和看过的 Jest 教程,其中很多都非常详细,但似乎没有一个适用于这种特殊情况。
甚至可以测试这段代码吗?如果是这样,如何?如果没有,我应该如何重构我的代码以便我可以测试它?
如果有人能指出正确的方向,我将不胜感激。
最佳答案
如果您将模拟函数作为 thirdPartyAPI.field.onValueChanged
传递给您的组件,那么它将通过 this.handleValueChange
被调用。
模拟函数记录它们被调用的所有内容,因此您可以使用模拟函数通过 mockFn.mock.calls
获取 this.handleValueChange
.
在测试中检索到 this.handleValueChange
后,您可以直接调用它并验证它是否按预期工作。
这是一个简单的工作示例:
import * as React from 'react';
import { shallow } from 'enzyme';
class App extends React.Component {
constructor(...args) {
super(...args);
this.state = { val: 'original' };
}
componentDidMount() {
const { thirdPartyAPI } = this.props;
thirdPartyAPI.field.onValueChanged(this.handleValueChange);
}
handleValueChange = (value) => {
this.setState({ val: value });
}
render() { return null; }
}
test('App', () => {
const onValueChangedMock = jest.fn();
const thirdPartyAPIMock = { field: { onValueChanged: onValueChangedMock } };
const wrapper = shallow(<App thirdPartyAPI={thirdPartyAPIMock} />);
expect(wrapper.state('val')).toBe('original'); // Success!
const handleValueChange = onValueChangedMock.mock.calls[0][0]; // <= get handleValueChange...
handleValueChange('updated'); // <= ...now call it directly
expect(wrapper.state('val')).toBe('updated'); // Success!
})
关于javascript - 如何 Jest 测试与第三方 API 一起使用的自定义回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56009056/