当我尝试测试反应组件时,我从其他未导入测试模块的组件中获取错误。
如果我导入了模块,我会发现这些错误会发生,因为我目前正在重构很多代码并且还没有完成这些文件。
在测试之前,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'
?
答案 0 :(得分:3)
当你String[][] arr = new String[][]{
{"New Delhi", "5000"},
{"Chennai", "4300"},
{"Goa", "2940"},
{"New Delhi", "2003"},
{"Kolkata", "8904"},
{"Kerala", "8972"},
{"New Delhi", "8922"},
{"Chennai", "8217"},
{"New Delhi", "2462"},
{"Kolkata", "5564"},
{"Kerala", "9406"}};
一个模块时,它将解析它的所有依赖关系。您的import
必须在某个时候导入AppWrap
。
您可以启用auto mock来缩小深度,或者您可以使用jest.mock手动模拟所有子模块,两者都会在需要时用模拟版本替换模块。