【发布时间】:2019-12-04 08:29:33
【问题描述】:
我正在尝试使用 sinon 对 Reacts useState 挂钩,但我遇到了问题。
这是我的组件的一个示例:
import React, { useState } from 'react';
function Expand() {
const [expanded, setExpanded] = useState(null);
return (
<div>
<button onClick={() => setExpanded(true)}>
Expand
</button>
</div>
);
}
我已经尝试过像这样使用诗乃来模拟它。
import * as React from 'react';
import {stub} from 'sinon';
const component = mount(<Expand />);
const setExpandedStub = stub();
const setStateStub = stub(React, 'useState').returns([
null,
setExpandedStub,
]);
component
.find('button')
.prop('onClick')();
t.equals(
setExpandedStub.args[0],
true,
'Should set the state to true.'
);
我遇到的问题是setExpandedStub.args 似乎永远不会返回我期望的结果。相反,它返回[]。我已经注销了钩子调用,它确实在测试中触发了,但我似乎无法弄清楚如何取回用于测试目的的内容。我这样做的原因是因为我似乎无法在 Enzyme 中调用 component.state(),因为它不是类组件。
【问题讨论】:
-
也许你的例子被简化了,但你为什么需要存根呢?如果目标是在触发单击按钮后测试状态是否为真,为什么不直接触发单击(如果使用酶,则使用模拟())并检查状态值是否为真?
-
@AlexanderStaroselsky 它被简化了,但据我了解,您不能在非类组件中使用 Enzyme 的
.state(),所以我想看看setExpanded被调用以确保状态是正确的。