对组件的测试中的React设置状态

发布于 2025-01-30 20:13:24 字数 746 浏览 2 评论 0原文

我正在尝试为我的recaptcha组件编写测试。我有一个有条件的声明,即如果网站密钥为true/具有值,则返回recaptcha。这是美国。

Const [reCaptchaKey, setReCaptchaKey] = useState(null);

这是我要测试的代码的一个示例。没有任何道具将其带入测试的组件中。

{recaptchaKey && (
  <div>
    <ReCAPTCHA ....
  </div>
  )}

这就是我到目前为止的。

test('No error', async () => {
  const recaptchaKey = 'key123';
  const setRecaptchaKey = () => {return recaptchaKey};
  const component = shallow(
  <ReCaptcha recaptchaKey={recaptchaKey} 
    setRecaptchaKey={setRecaptchaKey} /> 
  );
    expect(component).toMatchSnapshot();
})

我知道上述代码不起作用,我尝试使用jest.fn(),尽管我认为我没有正确使用它。我可能应该说,如果我记录了键,它将返回“ null”,这样我就可以用一只手来弄清楚如何将其设置为true。

I am trying to write tests for my ReCaptcha component. I have got a conditional statement that if the Site Key is true/has a value, then the ReCaptcha is returned. This is the useState.

Const [reCaptchaKey, setReCaptchaKey] = useState(null);

This is an example of the code that I am trying to test. There are no props that are taken into the component that have a bearing on the test.

{recaptchaKey && (
  <div>
    <ReCAPTCHA ....
  </div>
  )}

This is what I have so far.

test('No error', async () => {
  const recaptchaKey = 'key123';
  const setRecaptchaKey = () => {return recaptchaKey};
  const component = shallow(
  <ReCaptcha recaptchaKey={recaptchaKey} 
    setRecaptchaKey={setRecaptchaKey} /> 
  );
    expect(component).toMatchSnapshot();
})

The above code I know isn't working, I have tried using jest.fn() although I reckon I haven't used it correctly. I should probably say the that if I log out the key it is returning 'null' so I could just do with a hand with working out how to set that to true for example.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文