为什么Jest尝试运行我的整个应用程序而不是导入的模块?

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

当我尝试测试react组件时,我从未导入测试模块的其他组件中获取错误。

如果我导入了模块,我希望会发生这些错误,因为我目前正在重构很多代码并且还没有完成这些文件。

这几乎就像Jest在测试之前运行我的所有组件一样。以下是导致此问题的测试文件之一:

import React from 'react';
import { LoginPage } from 'components';

describe('Login Page', () => {
  it('should render', () => {
    expect(shallow(<LoginPage />)).toMatchSnapshot();
  });
  it('should use background passed into props', () => {
    const image = 'bg.png';
    const expected = {
      backgroundImage: image
    };
    const wrapper = shallow(<LoginPage background={image} />);
    expect(wrapper.prop('style')).toEqual(expected);
  });
});

Loginpage.js

import React from 'react';
import { LoginForm } from 'components';
import './LoginPage.css';

type Props = { background: string , logInRequest: Function};

const LoginPage = ({ background, logInRequest }: Props) => (
  <div className="login-page" style={{backgroundImage: background}}>
    <LoginForm submit={logInRequest}/>
  </div>
);

这是setupTests.js

import Enzyme, { shallow, mount, render } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import localStorage from 'mock-local-storage';

Enzyme.configure({ adapter: new Adapter() });

global.requestAnimationFrame = function(callback) {
  setTimeout(callback, 0);
};

global.shallow = shallow;
global.mount = mount;
global.render = render;
console.log = () => ({});

堆栈跟踪:

  at invariant (node_modules/invariant/invariant.js:42:15)
  at wrapWithConnect (node_modules/react-redux/lib/components/connectAdvanced.js:101:29)
  at Object.<anonymous> (src/containers/ApplicationList/ApplicationList.js:8:42)
  at Object.<anonymous> (src/containers/index.js:9:41)
  at Object.<anonymous> (src/components/CustomerDashboard/CustomerDashboard.js:2:19)
  at Object.<anonymous> (src/components/index.js:14:43)
  at Object.<anonymous> (src/components/LoginPage/LoginPage.test.js:2:19)
      at <anonymous>
  at process._tickCallback (internal/process/next_tick.js:188:7)

从读取堆栈跟踪,我可以假设Jest正在检查components/index.jscontainers/index.js中的导出列表。

为什么开玩笑会关注来自出口清单的错误?我没有将containers/ApplicationList导入LoginPage,它只通过导出列表作为依赖项引用。

我发现,如果我从导出列表中删除CustomerDashboard,问题就会消失,这对我说这不是导入LoginPage的问题

我应该使用像import LoginPage from './LoginPage这样的相对导入与LoginPage相同的目录而不是import { LoginPage } from 'components'进行测试吗?

javascript reactjs jestjs create-react-app
1个回答
3
投票

当你import一个模块时,它将解决它的所有依赖关系。你的AppWrap必须在某些时候导入PaymentAccountForm

您可以启用auto mock来缩小深度,或者您可以使用jest.mock手动模拟所有子模块,它们将在需要时将模块替换为模拟版本。

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