【问题标题】:Stubbing React useState with Sinon使用 Sinon 存根 React useState
【发布时间】: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 被调用以确保状态是正确的。

标签: reactjs enzyme sinon


【解决方案1】:

发生这种情况的原因有点难以解释。当您存根时,您正在存根对象的方法。因此,当您希望您的源代码受到存根的影响时,您还必须在那里使用存根对象。在这种情况下,您需要调用React.useState,而不是useState 的解构实例。

这应该可以解决您的问题:

import React from 'react';

function Expand() {
  const [expanded, setExpanded] = React.useState(null);

  return (
    <div>
      <button onClick={() => setExpanded(true)}>
        Expand
      </button>
    </div>
  );
}

【讨论】:

    猜你喜欢
    • 2014-08-08
    • 2018-07-16
    • 2016-08-09
    • 2014-11-29
    • 2020-12-12
    • 1970-01-01
    • 2015-11-28
    • 2021-07-26
    • 1970-01-01
    相关资源
    最近更新 更多