![](/img/trans.png)
[英]How to run two describe blocks sequentially in a mocha-chai test suite
[英]React Mocha-chai test not recognizing store from prop
我在Redux連接的React組件上進行了Mocha-chai測試。 為了將Redux存儲傳遞給測試組件,我在測試文件中創建它並將其作為prop傳遞,但測試會拋出以下錯誤:
不變違規:無法在“連接(項目)”的上下文或道具中找到“存儲”。 將根組件包裝在<Provider>中,或者將“store”顯式傳遞為“Connect(Project)”的prop。
這是測試:
import React from 'react';
import ReactDOM from 'react-dom';
import {
renderIntoDocument,
scryRenderedComponentsWithType
} from 'react-dom/test-utils';
import Project from '../../src/components/Project';
import { expect } from 'chai';
import { createStore } from 'redux';
import reducer from '../../src/reducers/reducers';
const store = createStore(reducer);
const component = renderIntoDocument(
<Project
store={ store }
project={
{
"name": "MyName",
"img": "path.jpg",
"img_alt": "alt desc",
"description": "lorem ipsum",
"github": "repository",
"link": "website.com"
}
} />
);
describe('Project', () => {
// tests ...
});
這是React組件:
import React from 'react';
import ProjectImage from './ProjectImage';
import ProjectText from './ProjectText';
import { connect } from 'react-redux';
import * as actions from '../actions/actions';
export const Project = React.createClass({
getProject: function() {
return this.props.project || {};
},
handleClick: function(event) {
this.props.dispatch(actions.showModal(true));
this.props.dispatch(
actions.setModalContent(this.getProject())
);
},
render: function() {
return (
<div className="project">
<ProjectImage
img={ this.getProject().img }
imgAlt={ this.getProject().img_alt }
link={ this.getProject().link } />
<ProjectText
projectName={ this.getProject().name }
tagline={ this.getProject().tagline }
description={ this.getProject.description }
github={ this.getProject().github }
webLink={ this.getProject().link }
openModal={ this.handleClick } />
</div>
);
}
});
export default connect()(Project);
為什么在沒有mapStateToProps
或mapDispatchToProps
函數的情況下使用connect
for Project
組件?
但是......沒有必要將包裝組件測試到connect
。 您只需要測試普通Project
組件。
如何導出這兩個組件? - 請在同一問題上關注此鏈接 。
要解決此問題,您可以執行以下操作:
安裝名為redux-mock-store npm install redux-mock-store
像這樣設置商店:
import configureStore from 'redux-mock-store';
const middlewares = [];
const mockStore = configureStore(middlewares);
添加您想要包含在商店中的任何中間件,例如。 redux-thunk,redux-sagas等
定義您的初始狀態,並按如下方式創建您的商店:
initialState = {}
const store = mockStore(initialState);
然后將新商店連接到您正在測試的組件:
const component = renderIntoDocument(
<Project
store={ store }
project={
{
"name": "MyName",
"img": "path.jpg",
"img_alt": "alt desc",
"description": "lorem ipsum",
"github": "repository",
"link": "website.com"
}
} />
);
describe('Project', () => {
// tests ...
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.