使用玩笑和酵素测试useEffect和useState

问题描述 投票:1回答:1

如何一次测试useEffect,所以我正在装载许多链接。因此它只会被调用一次

查看代码

app.js

import React, { useState, useEffect } from "react";

const App = () => {
    const [links, setLinks] = useState([]);

    useEffect(() => {
        const links = createLinks();
        setLinks(links);
    }, []);

    const createLinks = () => {
        return [{ link: "https://www.google.com", text: "Google" }];
    };

    return <>{links.length && links.map(({ link, text }) => <a href={link}>{text}</a>)}</>;
};


export default App

我如何使用笑话和酶为上述示例应用程序组件编写测试用例

reactjs jestjs enzyme
1个回答
0
投票

这里是单元测试解决方案:

index.ts

import React, { useState, useEffect } from "react";

const App = () => {
  const [links, setLinks] = useState([]);

  useEffect(() => {
    const newLinks = createLinks();
    // @ts-ignore
    setLinks(newLinks);
  }, []);

  const createLinks = () => {
    return [{ link: "https://www.google.com", text: "Google" }];
  };

  return (
    <>
      {links.length &&
        links.map(({ link, text }, idx) => (
          <a key={idx} href={link}>
            {text}
          </a>
        ))}
    </>
  );
};

export default App;

index.spec.tsx

import React from "react";
import App from "./";
import { mount } from "enzyme";

describe("App", () => {
  it("should pass", () => {
    const wrapper = mount(<App></App>);
    expect(wrapper).toMatchInlineSnapshot(`
      <App>
        <a
          href="https://www.google.com"
          key="0"
        >
          Google
        </a>
      </App>
    `);
  });
});

单元测试结果覆盖率100%:

PASS  src/stackoverflow/59169619/index.spec.tsx (9.657s)
  App
    ✓ should pass (57ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |      100 |      100 |                   |
 index.tsx |      100 |      100 |      100 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   1 passed, 1 total
Time:        11.237s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59169619

© www.soinside.com 2019 - 2024. All rights reserved.