【发布时间】:2025-12-01 22:20:03
【问题描述】:
这是我的反应组件:
import { sendAnalytics } from 'analytics';
class MyComponent extends React.Component {
myMethod() {
console.log('do something!');
}
render() {
return (
<Button
onClick={submitAnalytics({name: 'foo'}).finally(this.myMethod())}
dataset={{"data-id": "button"}}
> Send Analytics
</Button>
}
)
}
}
而我的测试是这样的:
import * as analytics from 'analytics';
jest.mock('analytics');
describe('Analytics', () => {
it('Should call analytics when button is clicked', () => {
analytics.submitAnalytics.mockResolvedValue(Promise.resolve(true));
const tree = ReactTestRenderer.create(<MyComponent />);
// Actual implementation of following 3 lines is slightly different.
const button = tree.root.findByProps({"data-id": "button"});
button.props.onClick();
expect(analytics.submitAnalytics).toHaveBeenCalled();
});
});
我尝试了几种不同的模拟策略,例如:
analytics.submitAnalytics.mockImplementation(() => {
return Promise.resolve(true)
});
似乎没有任何结果。我不断收到以下错误:
TypeError: (0 , analytics.submitAnalytics)(...).finally is not a function.
我不知道为什么。任何帮助表示赞赏。 如果您需要更多上下文代码,请告诉我。
【问题讨论】:
-
您是否尝试过返回一个新的 Promise 而不是返回 resolve 方法的结果?
-
是的,我做到了。
标签: javascript reactjs jestjs