当我尝试测试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.js
和containers/index.js
中的导出列表。
为什么开玩笑会关注来自出口清单的错误?我没有将containers/ApplicationList
导入LoginPage
,它只通过导出列表作为依赖项引用。
我发现,如果我从导出列表中删除CustomerDashboard
,问题就会消失,这对我说这不是导入LoginPage
的问题
我应该使用像import LoginPage from './LoginPage
这样的相对导入与LoginPage
相同的目录而不是import { LoginPage } from 'components'
进行测试吗?