开玩笑的路由单元测试

时间:2020-03-04 22:39:47

标签: javascript reactjs unit-testing jestjs

我正在尝试编写一个简单的测试,以检查我的React应用程序中的底部导航是否正常运行。 BottomNav.test.js 中的单元测试如下:

BottomNav.js(相关代码):

<div className="BottomNav">
    <div>
        <NavLink to="/home" id="home">
            <FaHome aria-label="Home"/>
        </NavLink>
    </div>
</div>

BottomNav.test.js:

let container = null;

beforeEach(() => {
  container = document.createElement('div');
  document.body.appendChild(container);

  render(
    <MemoryRouter>
      <BottomNav />
    </MemoryRouter>,
    container
  );

});

afterEach(() => {
  unmountComponentAtNode(container);
  container.remove();
  container = null;
});

test('navigates home when Home is selected', async => {

  act(() => {
    const link = document.querySelector('#home');
    link.dispatchEvent(new MouseEvent('click', {bubbles: true}));
  });

  expect(location.pathname).toBe('/home');
}); 

此测试运行,但是具有以下测试结果:

expect(received).toBe(expected)// Object.is相等

预期:“ / home”

收到:“ /”

我尝试如下更改testURL配置:

//package.json
...,
"jest": {
     "testURL": "http://localhost:3000/"
},
...

导致此错误的原因:

开箱即用,Create React App仅支持覆盖这些Jest 选项:

•clearMocks
•collectCoverageFrom
•coveragePathIgnorePatterns •coverageReporters
•coverageThreshold
•displayName
•extraGlobals
•globalSetup
•globalTeardown
•moduleNameMapper
•resetMocks •resetModules
•restoreMocks
•snapshotSerializers •转换
•transformIgnorePatterns
•watchPathIgnorePatterns。

package.json Jest配置中的这些选项不是 目前由Create React App支持:

•testURL

如果我在BottomNav.test.js中将expect(location.pathname).toBe('/home');更改为expect(location.pathname).toBe('/');,则会收到以下错误,因此即使应该成功的这种情况也会失败:

在指定的5000ms超时内未调用异步回调 jest.setTimeout.Timeout-异步回调未在 jest.setTimeout.Error指定的5000ms超时

所以在这一点上我很茫然。看起来该测试陷入无限循环或试图单击导航按钮的过程中,从而在该测试成功的情况下导致超时错误。

TL; DR 如何在Jest中编写测试以查看按导航按钮是否加载正确的屏幕?

0 个答案:

没有答案