고정 위반 : "Connect (SportsDatabase)"의 컨텍스트 또는 소품에서 "store"를 찾을 수 없습니다.
전체 코드 : https://gist.github.com/js08/0ec3d70dfda76d7e9fb4
안녕하세요,
- 빌드 환경에 따라 데스크톱과 모바일에 대해 서로 다른 템플릿을 보여주는 응용 프로그램이 있습니다.
- 모바일 템플릿의 탐색 메뉴를 숨겨야하는 곳에서 성공적으로 개발할 수 있습니다.
- 지금은 proptypes를 통해 모든 값을 가져오고 올바르게 렌더링하는 하나의 테스트 케이스를 작성할 수 있습니다.
- 그러나 모바일에서 nav 구성 요소를 렌더링해서는 안되는 단위 테스트 케이스를 작성하는 방법을 모르겠습니다.
- 시도했지만 오류가 발생했습니다 ... 해결 방법을 알려주세요.
- 아래 코드를 증명하십시오.
테스트 케이스
import {expect} from 'chai';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import {SportsTopPortion} from '../../../src/components/sports-top-portion/sports-top-portion.jsx';
require('../../test-utils/dom');
describe('"sports-top-portion" Unit Tests', function() {
let shallowRenderer = TestUtils.createRenderer();
let sportsContentContainerLayout ='mobile';
let sportsContentContainerProfile = {'exists': 'hasSidebar'};
let sportsContentContainerAuthExchange = {hasValidAccessToken: true};
let sportsContentContainerHasValidAccessToken ='test';
it('should render correctly', () => {
shallowRenderer.render(<SportsTopPortion sportsWholeFramework={sportsContentContainerLayout} sportsPlayers={sportsContentContainerProfile} sportsAuthentication={sportsContentContainerAuthExchange} sportsUpperBar={{activeSportsLink:'test'}} />);
//shallowRenderer.render(<SportsTopPortion sportsWholeFramework={sportsContentContainerLayout} sportsPlayers={sportsContentContainerProfile} hasValidAccessToken={sportsContentContainerHasValidAccessToken} />);
let renderedElement = shallowRenderer.getRenderOutput();
console.log("renderedElement------->" + JSON.stringify(renderedElement));
expect(renderedElement).to.exist;
});
it('should not render sportsNavigationComponent when sports.build is mobile', () => {
let sportsNavigationComponent = TestUtils.renderIntoDocument(<SportsTopPortion sportsWholeFramework={sportsContentContainerLayout} sportsPlayers={sportsContentContainerProfile} sportsAuthentication={sportsContentContainerAuthExchange} sportsUpperBar={{activeSportsLink:'test'}} />);
console.log("sportsNavigationComponent------->" + JSON.stringify(sportsNavigationComponent));
//let footnoteContainer = TestUtils.findRenderedDOMComponentWithClass(sportsNavigationComponent, 'linkPack--standard');
//expect(footnoteContainer).to.exist;
});
});
테스트 케이스를 작성해야하는 코드 스 니펫
if (sports.build === 'mobile') {
sportsNavigationComponent = <div />;
sportsSideMEnu = <div />;
searchComponent = <div />;
sportsPlayersWidget = <div />;
}
오류
1) "sports-top-portion" Unit Tests should not render sportsNavigationComponent when sports.build is mobile:
Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(SportsDatabase)".
at Object.invariant [as default] (C:\sports-whole-page\node_modules\invariant\invariant.js:42:15)
at new Connect (C:\sports-whole-page\node_modules\react-redux\lib\components\createConnect.js:135:33)
at [object Object].ReactCompositeComponentMixin.mountComponent (C:\sports-whole-page\node_modules\react\lib\ReactCompositeComponent.js:148:18)
at [object Object].wrapper [as mountComponent] (C:\sports-whole-page\node_modules\react\lib\ReactPerf.js:66:21)
at Object.ReactReconciler.mountComponent (C:\sports-whole-page\node_modules\react\lib\ReactReconciler.js:37:35)
at ReactDOMComponent.ReactMultiChild.Mixin.mountChildren (C:\sports-whole-page\node_modules\react\lib\ReactMultiChild.js:241:44)
at ReactDOMComponent.Mixin._createContentMarkup (C:\sports-whole-page\node_modules\react\lib\ReactDOMComponent.js:591:32)
at ReactDOMComponent.Mixin.mountComponent (C:\sports-whole-page\node_modules\react\lib\ReactDOMComponent.js:479:29)
at Object.ReactReconciler.mountComponent (C:\sports-whole-page\node_modules\react\lib\ReactReconciler.js:37:35)
at ReactDOMComponent.ReactMultiChild.Mixin.mountChildren (C:\sports-whole-page\node_modules\react\lib\ReactMultiChild.js:241:44)
at ReactDOMComponent.Mixin._createContentMarkup (C:\sports-whole-page\node_modules\react\lib\ReactDOMComponent.js:591:32)
at ReactDOMComponent.Mixin.mountComponent (C:\sports-whole-page\node_modules\react\lib\ReactDOMComponent.js:479:29)
at Object.ReactReconciler.mountComponent (C:\sports-whole-page\node_modules\react\lib\ReactReconciler.js:37:35)
at [object Object].ReactCompositeComponentMixin.mountComponent (C:\sports-whole-page\node_modules\react\lib\ReactCompositeComponent.js:225:34)
at [object Object].wrapper [as mountComponent] (C:\sports-whole-page\node_modules\react\lib\ReactPerf.js:66:21)
at Object.ReactReconciler.mountComponent (C:\sports-whole-page\node_modules\react\lib\ReactReconciler.js:37:35)
at ReactDOMComponent.ReactMultiChild.Mixin.mountChildren (C:\sports-whole-page\node_modules\react\lib\ReactMultiChild.js:241:44)
at ReactDOMComponent.Mixin._createContentMarkup (C:\sports-whole-page\node_modules\react\lib\ReactDOMComponent.js:591:32)
at ReactDOMComponent.Mixin.mountComponent (C:\sports-whole-page\node_modules\react\lib\ReactDOMComponent.js:479:29)
at Object.ReactReconciler.mountComponent (C:\sports-whole-page\node_modules\react\lib\ReactReconciler.js:37:35)
at [object Object].ReactCompositeComponentMixin.mountComponent (C:\sports-whole-page\node_modules\react\lib\ReactCompositeComponent.js:225:34)
at [object Object].wrapper [as mountComponent] (C:\sports-whole-page\node_modules\react\lib\ReactPerf.js:66:21)
at Object.ReactReconciler.mountComponent (C:\sports-whole-page\node_modules\react\lib\ReactReconciler.js:37:35)
at ReactDOMComponent.ReactMultiChild.Mixin.mountChildren (C:\sports-whole-page\node_modules\react\lib\ReactMultiChild.js:241:44)
at ReactDOMComponent.Mixin._createContentMarkup (C:\sports-whole-page\node_modules\react\lib\ReactDOMComponent.js:591:32)
at ReactDOMComponent.Mixin.mountComponent (C:\sports-whole-page\node_modules\react\lib\ReactDOMComponent.js:479:29)
at Object.ReactReconciler.mountComponent (C:\sports-whole-page\node_modules\react\lib\ReactReconciler.js:37:35)
at [object Object].ReactCompositeComponentMixin.mountComponent (C:\sports-whole-page\node_modules\react\lib\ReactCompositeComponent.js:225:34)
at [object Object].wrapper [as mountComponent] (C:\sports-whole-page\node_modules\react\lib\ReactPerf.js:66:21)
at Object.ReactReconciler.mountComponent (C:\sports-whole-page\node_modules\react\lib\ReactReconciler.js:37:35)
at [object Object].ReactCompositeComponentMixin.mountComponent (C:\sports-whole-page\node_modules\react\lib\ReactCompositeComponent.js:225:34)
at [object Object].wrapper [as mountComponent] (C:\sports-whole-page\node_modules\react\lib\ReactPerf.js:66:21)
at Object.ReactReconciler.mountComponent (C:\sports-whole-page\node_modules\react\lib\ReactReconciler.js:37:35)
at mountComponentIntoNode (C:\sports-whole-page\node_modules\react\lib\ReactMount.js:266:32)
at ReactReconcileTransaction.Mixin.perform (C:\sports-whole-page\node_modules\react\lib\Transaction.js:136:20)
at batchedMountComponentIntoNode (C:\sports-whole-page\node_modules\react\lib\ReactMount.js:282:15)
at ReactDefaultBatchingStrategyTransaction.Mixin.perform (C:\sports-whole-page\node_modules\react\lib\Transaction.js:136:20)
at Object.ReactDefaultBatchingStrategy.batchedUpdates (C:\sports-whole-page\node_modules\react\lib\ReactDefaultBatchingStrategy.js:62:19)
at Object.batchedUpdates (C:\sports-whole-page\node_modules\react\lib\ReactUpdates.js:94:20)
at Object.ReactMount._renderNewRootComponent (C:\sports-whole-page\node_modules\react\lib\ReactMount.js:476:18)
at Object.wrapper [as _renderNewRootComponent] (C:\sports-whole-page\node_modules\react\lib\ReactPerf.js:66:21)
at Object.ReactMount._renderSubtreeIntoContainer (C:\sports-whole-page\node_modules\react\lib\ReactMount.js:550:32)
at Object.ReactMount.render (C:\sports-whole-page\node_modules\react\lib\ReactMount.js:570:23)
at Object.wrapper [as render] (C:\sports-whole-page\node_modules\react\lib\ReactPerf.js:66:21)
at Object.ReactTestUtils.renderIntoDocument (C:\sports-whole-page\node_modules\react\lib\ReactTestUtils.js:76:21)
at Context.<anonymous> (C:/codebase/sports-whole-page/test/components/sports-top-portion/sports-top-portion-unit-tests.js:28:41)
at callFn (C:\sports-whole-page\node_modules\mocha\lib\runnable.js:286:21)
at Test.Runnable.run (C:\sports-whole-page\node_modules\mocha\lib\runnable.js:279:7)
at Runner.runTest (C:\sports-whole-page\node_modules\mocha\lib\runner.js:421:10)
at C:\sports-whole-page\node_modules\mocha\lib\runner.js:528:12
at next (C:\sports-whole-page\node_modules\mocha\lib\runner.js:341:14)
at C:\sports-whole-page\node_modules\mocha\lib\runner.js:351:7
at next (C:\sports-whole-page\node_modules\mocha\lib\runner.js:283:14)
at Immediate._onImmediate (C:\sports-whole-page\node_modules\mocha\lib\runner.js:319:5)
It's pretty simple. You're trying to test the wrapper component generated by calling connect()(MyPlainComponent)
. That wrapper component expects to have access to a Redux store. Normally that store is available as context.store
, because at the top of your component hierarchy you'd have a <Provider store={myStore} />
. However, you're rendering your connected component by itself, with no store, so it's throwing an error.
You've got a few options:
- Create a store and render a
<Provider>
around your connected component - Create a store and directly pass it in as
<MyConnectedComponent store={store} />
, as the connected component will also accept "store" as a prop - Don't bother testing the connected component. Export the "plain", unconnected version, and test that instead. If you test your plain component and your
mapStateToProps
function, you can safely assume the connected version will work correctly.
You probably want to read through the "Testing" page in the Redux docs: https://redux.js.org/recipes/writing-tests.
edit:
After actually seeing that you posted source, and re-reading the error message, the real problem is not with the SportsTopPane component. The problem is that you're trying to "fully" render SportsTopPane, which also renders all of its children, rather than doing a "shallow" render like you were in the first case. The line searchComponent = <SportsDatabase sportsWholeFramework="desktop" />;
is rendering a component that I assume is also connected, and therefore expects a store to be available in React's "context" feature.
At this point, you have two new options:
- Only do "shallow" rendering of SportsTopPane, so that you're not forcing it to fully render its children
- If you do want to do "deep" rendering of SportsTopPane, you'll need to provide a Redux store in context. I highly suggest you take a look at the Enzyme testing library, which lets you do exactly that. See http://airbnb.io/enzyme/docs/api/ReactWrapper/setContext.html for an example.
Overall, I would note that might be trying to do too much in this one component. You might want to consider breaking it into smaller pieces with less logic per component.
Possible solution that worked for me with jest
import React from "react";
import { shallow } from "enzyme";
import { Provider } from "react-redux";
import configureMockStore from "redux-mock-store";
import TestPage from "../TestPage";
const mockStore = configureMockStore();
const store = mockStore({});
describe("Testpage Component", () => {
it("should render without throwing an error", () => {
expect(
shallow(
<Provider store={store}>
<TestPage />
</Provider>
).exists(<h1>Test page</h1>)
).toBe(true);
});
});
As the official docs of redux suggest, better to export the unconnected component as well.
In order to be able to test the App component itself without having to deal with the decorator, we recommend you to also export the undecorated component:
import { connect } from 'react-redux'
// Use named export for unconnected component (for tests)
export class App extends Component { /* ... */ }
// Use default export for the connected component (for app)
export default connect(mapStateToProps)(App)
Since the default export is still the decorated component, the import statement pictured above will work as before so you won't have to change your application code. However, you can now import the undecorated App components in your test file like this:
// Note the curly braces: grab the named export instead of default export
import { App } from './App'
And if you need both:
import ConnectedApp, { App } from './App'
In the app itself, you would still import it normally:
import App from './App'
You would only use the named export for tests.
When we put together a react-redux application we should expect to see a structure where at the top we have the Provider
tag which has an instance of a redux store.
That Provider
tag then renders your parent component, lets call it the App
component which in turn renders every other component inside the application.
Here is the key part, when we wrap a component with the connect()
function, that connect()
function expects to see some parent component within the hierarchy that has the Provider
tag.
So the instance you put the connect()
function in there, it will look up the hierarchy and try to find the Provider
.
Thats what you want to have happen, but in your test environment that flow is breaking down.
Why?
Why?
When we go back over to the assumed sportsDatabase test file, you must be the sportsDatabase component by itself and then trying to render that component by itself in isolation.
So essentially what you are doing inside that test file is just taking that component and just throwing it off in the wild and it has no ties to any Provider
or store above it and thats why you are seeing this message.
There is not store or Provider
tag in the context or prop of that component and so the component throws an error because it want to see a Provider
tag or store in its parent hierarchy.
So that’s what that error means.
in my case just
const myReducers = combineReducers({
user: UserReducer
});
const store: any = createStore(
myReducers,
applyMiddleware(thunk)
);
shallow(<Login />, { context: { store } });
'programing tip' 카테고리의 다른 글
Vim에서 텍스트를 일정 길이로 줄 바꿈하려면 어떻게해야합니까? (0) | 2020.08.20 |
---|---|
jquery가로드 될 때까지 스크립트 실행을 대기시키는 방법 (0) | 2020.08.20 |
그룹화를 사용하여 목록에 사전 만들기 (0) | 2020.08.20 |
Mapbox 또는 Leaflet의 모든 마커에 맞게 확대 (0) | 2020.08.20 |
AWK를 배울 이유가 아직 있습니까? (0) | 2020.08.20 |