使用 useEffect() 钩子来测试 Jest 中的函数

MK6*_*MK6 5 unit-testing reactjs jestjs use-effect use-state

我基本上正在学习 Jest,我必须为 useEffect() 钩子编写一个测试用例,该钩子基于 flag[counter] 进行渲染,并在内部检查字段是否存在 localStorage 值。

function sample(props) {
  const counter = props;
  const [displayIcon, setDisplayIcon] = useState(counter);

  function isLocalstoragePresent() {    
    return localStorage.getItem("some_Id");
  }

  useEffect(() => {
    if (isLocalstoragePresent()) {
      setDisplayIcon(true);
    } else {
      setDisplayIcon(false);
    }
  }, [counter]);

 export default sample;
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我编写测试用例/为内部调用 isLocalstoragePresent() 方法的 UseEffect 提供指导吗?提前致谢。

sli*_*wp2 5

jestjs这是使用和 的单元测试解决方案react-dom/test-utils

\n\n

index.tsx:

\n\n
import React, { useState, useEffect } from \'react\';\n\nfunction sample(props) {\n  const { counter } = props;\n  const [displayIcon, setDisplayIcon] = useState(counter);\n\n  function isLocalstoragePresent() {\n    return localStorage.getItem(\'some_Id\');\n  }\n\n  useEffect(() => {\n    if (isLocalstoragePresent()) {\n      setDisplayIcon(true);\n    } else {\n      setDisplayIcon(false);\n    }\n  }, [counter]);\n\n  return <div>{displayIcon ? \'icon\' : \'\'}</div>;\n}\n\nexport default sample;\n
Run Code Online (Sandbox Code Playgroud)\n\n

index.test.tsx:

\n\n
import Sample from \'./\';\nimport React from \'react\';\nimport { render, unmountComponentAtNode } from \'react-dom\';\nimport { act } from \'react-dom/test-utils\';\n\ndescribe(\'60639673\', () => {\n  let container;\n  beforeEach(() => {\n    container = document.createElement(\'div\');\n    document.body.appendChild(container);\n  });\n\n  afterEach(() => {\n    unmountComponentAtNode(container);\n    container.remove();\n    container = null;\n  });\n\n  it(\'should display icon\', async () => {\n    jest.spyOn(localStorage.__proto__, \'getItem\').mockReturnValueOnce(\'1\');\n    const mProps = { counter: false };\n    await act(async () => {\n      render(<Sample {...mProps}></Sample>, container);\n    });\n    expect(container.querySelector(\'div\').textContent).toBe(\'icon\');\n    expect(localStorage.__proto__.getItem).toBeCalledWith(\'some_Id\');\n    localStorage.__proto__.getItem.mockRestore();\n  });\n\n  it(\'should not display icon\', async () => {\n    jest.spyOn(localStorage.__proto__, \'getItem\').mockReturnValueOnce(\'\');\n    const mProps = { counter: true };\n    await act(async () => {\n      render(<Sample {...mProps}></Sample>, container);\n    });\n    expect(container.querySelector(\'div\').textContent).toBe(\'\');\n    expect(localStorage.__proto__.getItem).toBeCalledWith(\'some_Id\');\n    localStorage.__proto__.getItem.mockRestore();\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
 PASS  stackoverflow/60639673/index.test.tsx (9.723s)\n  60639673\n    \xe2\x9c\x93 should display icon (41ms)\n    \xe2\x9c\x93 should not display icon (8ms)\n\n-----------|---------|----------|---------|---------|-------------------\nFile       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s \n-----------|---------|----------|---------|---------|-------------------\nAll files  |     100 |      100 |     100 |     100 |                   \n index.tsx |     100 |      100 |     100 |     100 |                   \n-----------|---------|----------|---------|---------|-------------------\nTest Suites: 1 passed, 1 total\nTests:       2 passed, 2 total\nSnapshots:   0 total\nTime:        11.242s\n
Run Code Online (Sandbox Code Playgroud)\n\n

依赖版本:

\n\n
"react": "^16.12.0",\n"react-dom": "^16.12.0",\n"jest": "^25.1.0"\n
Run Code Online (Sandbox Code Playgroud)\n\n

源代码:https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60639673

\n