Skip to content

Commit 6c3b9eb

Browse files
committed
add dynamic action creator unit test
1 parent 97825a1 commit 6c3b9eb

File tree

3 files changed

+47
-2
lines changed

3 files changed

+47
-2
lines changed

chapter-07/weather_redux/package.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
"proxy": "http://www.weather.com.cn/",
66
"devDependencies": {
77
"react-scripts": "0.8.4",
8-
"redux-immutable-state-invariant": "^1.2.4"
8+
"redux-immutable-state-invariant": "^1.2.4",
9+
"redux-mock-store": "^1.2.1",
10+
"sinon": "^1.17.7"
911
},
1012
"dependencies": {
1113
"react": "^15.4.1",

chapter-07/weather_redux/src/weather/actions.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ export const fetchWeather = (cityCode) => {
2020

2121
dispatch(fetchWeatherStarted())
2222

23-
fetch(apiUrl).then((response) => {
23+
return fetch(apiUrl).then((response) => {
2424
if (response.status !== 200) {
2525
throw new Error('Fail to get response with status ' + response.status);
2626
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import thunk from 'redux-thunk';
2+
import {stub} from 'sinon';
3+
import configureStore from 'redux-mock-store';
4+
5+
import * as actions from '../../src/weather/actions.js';
6+
import * as actionTypes from '../../src/weather/actionTypes.js';
7+
8+
const middlewares = [thunk];
9+
const createMockStore = configureStore(middlewares);
10+
11+
12+
describe('weather/actions', () => {
13+
describe('fetchWeather', () => {
14+
let stubbedFetch;
15+
const store = createMockStore();
16+
17+
beforeEach(() => {
18+
stubbedFetch = stub(global, 'fetch');
19+
});
20+
21+
afterEach(() => {
22+
stubbedFetch.restore();
23+
});
24+
25+
it('should dispatch fetchWeatherSuccess action type on fetch success', () => {
26+
const mockResponse= Promise.resolve({
27+
status: 200,
28+
json: () => Promise.resolve({
29+
weatherinfo: {}
30+
})
31+
});
32+
stubbedFetch.returns(mockResponse);
33+
34+
return store.dispatch(actions.fetchWeather(1)).then(() => {
35+
const dispatchedActions = store.getActions();
36+
expect(dispatchedActions.length).toBe(2);
37+
expect(dispatchedActions[0].type).toBe(actionTypes.FETCH_STARTED);
38+
expect(dispatchedActions[1].type).toBe(actionTypes.FETCH_SUCCESS);
39+
});
40+
});
41+
42+
});
43+
});

0 commit comments

Comments
 (0)