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

Why does Jest try running my whole app rather than the imported modules?

当我尝试测试一个反应组件时,我从其他未导入到测试模块中的组件中得到错误。

如果我导入了模块,我预计会发生这些错误,因为我目前正在重构大量代码并且还没有找到这些文件。

几乎就好像 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.

中的导出列表

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

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

的问题

我是否应该在与 LoginPage 相同的目录中使用 import LoginPage from './LoginPage 之类的相对导入而不是 import { LoginPage } from 'components'

当您 import 一个模块时,它会解析它的所有依赖项。您的 AppWrap 必须在某个时候导入 PaymentAccountForm

您可以启用auto mock to narrow the depth, or you can mock all sub module manually with jest.mock两者都将在需要时用模拟版本替换模块。