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

Emo*_*obe 8 javascript reactjs jestjs create-react-app

当我尝试测试 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);
  });
});
Run Code Online (Sandbox Code Playgroud)

登录页面.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>
);
Run Code Online (Sandbox Code Playgroud)

这是 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 = () => ({});
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪:

  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)
Run Code Online (Sandbox Code Playgroud)

从阅读堆栈跟踪,我可以假设玩笑正在检查内出口的清单components/index.jscontainers/index.js

为什么 jest 关心来自导出列表的错误?我没有导入containers/ApplicationListLoginPage,它只是通过导出列表作为依赖项引用。

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

我应该像import LoginPage from './LoginPage在同一目录中的测试一样使用相对导入LoginPage而不是import { LoginPage } from 'components'

Gab*_*leu 5

当您import使用模块时,它将解决其所有依赖项。您必须在某个时候AppWrap导入。PaymentAccountForm

您可以启用自动模拟来缩小深度,也可以使用jest.mock手动模拟所有子模块,两者都会在需要时用模拟版本替换模块。