-
Notifications
You must be signed in to change notification settings - Fork 406
Expand file tree
/
Copy pathtestServer.js
More file actions
266 lines (217 loc) · 8.15 KB
/
testServer.js
File metadata and controls
266 lines (217 loc) · 8.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import React from 'react';
import Helmet from 'react-helmet';
import { Router, Route } from 'react-router';
import { applyMiddleware, createStore, combineReducers } from 'redux';
import { reducer as reduxAsyncConnect } from 'redux-connect';
import createSagaMiddleware from 'redux-saga';
import NestedStatus from 'react-nested-status';
import supertest from 'supertest';
import defaultConfig, { util as configUtil } from 'config';
import cheerio from 'cheerio';
import baseServer from 'core/server/base';
import apiReducer from 'core/reducers/api';
import userReducer from 'core/reducers/user';
import userSaga from 'core/sagas/user';
import * as userApi from 'core/api/user';
import FakeApp, { fakeAssets } from 'tests/unit/core/server/fakeApp';
import { createUserProfileResponse, userAuthToken } from 'tests/unit/helpers';
describe(__filename, () => {
let mockUserApi;
const _helmetCanUseDOM = Helmet.canUseDOM;
const defaultStubRoutes = (
<Router>
<Route path="*" component={FakeApp} />
</Router>
);
beforeEach(() => {
Helmet.canUseDOM = false;
global.webpackIsomorphicTools = {
assets: () => fakeAssets,
};
mockUserApi = sinon.mock(userApi);
});
afterEach(() => {
Helmet.canUseDOM = _helmetCanUseDOM;
delete global.webpackIsomorphicTools;
});
function createStoreAndSagas({
reducers = { reduxAsyncConnect, api: apiReducer, user: userReducer },
} = {}) {
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
combineReducers(reducers),
// Do not define an initial state.
undefined,
applyMiddleware(sagaMiddleware),
);
return { store, sagaMiddleware };
}
function testClient({
stubRoutes = defaultStubRoutes,
store = null,
sagaMiddleware = null,
appSagas = null,
config = defaultConfig,
} = {}) {
function _createStoreAndSagas() {
if (store === null) {
return createStoreAndSagas();
}
return { store, sagaMiddleware };
}
// eslint-disable-next-line no-empty-function
function* fakeSaga() {}
const app = baseServer(stubRoutes, _createStoreAndSagas, {
appSagas: appSagas || fakeSaga,
appInstanceName: 'testapp',
config,
});
return supertest(app);
}
describe('app', () => {
it('varies on DNT', async () => {
const response = await testClient().get('/en-US/firefox/').end();
expect(response.headers).toMatchObject({ vary: 'DNT' });
expect(response.statusCode).toEqual(200);
});
it('returns the status code of NestedStatus', async () => {
// This is an example of implementing a NotFound component
// using NestedStatus which exercises the server's logic for
// getting the response status code from the rendered component.
class NotFound extends React.Component {
render() {
return (
<NestedStatus code={404}>
<h1>Not Found</h1>
</NestedStatus>
);
}
}
const stubRoutes = (
<Router>
<Route path="*" component={NotFound} />
</Router>
);
const response = await testClient({ stubRoutes })
.get('/en-US/firefox/simulation-of-a-non-existent-page')
.end();
expect(response.statusCode).toEqual(404);
});
it('does not dispatch setAuthToken() if cookie is not found', async () => {
const { store, sagaMiddleware } = createStoreAndSagas();
const response = await testClient({ store, sagaMiddleware })
.get('/en-US/firefox/')
.end();
const { api } = store.getState();
expect(response.statusCode).toEqual(200);
expect(api.token).toBe(null);
});
it('dispatches setAuthToken() if cookie is present', async () => {
const token = userAuthToken();
const { store, sagaMiddleware } = createStoreAndSagas();
const response = await testClient({ store, sagaMiddleware })
.get('/en-US/firefox/')
.set('cookie', `${defaultConfig.get('cookieName')}="${token}"`)
.end();
const { api } = store.getState();
expect(response.statusCode).toEqual(200);
expect(api.token).toEqual(token);
});
it('fetches the user profile when given a token', async () => {
const profile = createUserProfileResponse({ id: 42, username: 'babar' });
mockUserApi
.expects('userProfile')
.once()
.returns(Promise.resolve(profile));
const token = userAuthToken();
const { store, sagaMiddleware } = createStoreAndSagas();
const response = await testClient({ store, sagaMiddleware, appSagas: userSaga })
.get('/en-US/firefox/')
.set('cookie', `${defaultConfig.get('cookieName')}="${token}"`)
.end();
const { api, user } = store.getState();
expect(response.statusCode).toEqual(200);
expect(api.token).toEqual(token);
expect(user.id).toEqual(42);
expect(user.username).toEqual('babar');
mockUserApi.verify();
});
it('returns a 500 error page when retrieving the user profile fails', async () => {
mockUserApi
.expects('userProfile')
.once()
.rejects('example of an API error');
const token = userAuthToken();
const { store, sagaMiddleware } = createStoreAndSagas();
const response = await testClient({ store, sagaMiddleware, appSagas: userSaga })
.get('/en-US/firefox/')
.set('cookie', `${defaultConfig.get('cookieName')}="${token}"`)
.end();
expect(response.statusCode).toEqual(500);
mockUserApi.verify();
});
it('fetches the user profile even when SSR is disabled', async () => {
const profile = createUserProfileResponse({ id: 42, username: 'babar' });
mockUserApi
.expects('userProfile')
.once()
.returns(Promise.resolve(profile));
const token = userAuthToken();
const { store, sagaMiddleware } = createStoreAndSagas();
// We use `cloneDeep()` to allow modifications on the `config` object,
// since a call to `get()` makes it immutable. This is the case in the
// previous test cases (on `defaultConfig`).
const config = configUtil.cloneDeep(defaultConfig);
config.disableSSR = true;
const client = testClient({
store,
sagaMiddleware,
appSagas: userSaga,
config,
});
const response = await client
.get('/en-US/firefox/')
.set('cookie', `${defaultConfig.get('cookieName')}="${token}"`)
.end();
const { api, user } = store.getState();
expect(response.statusCode).toEqual(200);
expect(api.token).toEqual(token);
expect(user.id).toEqual(42);
expect(user.username).toEqual('babar');
mockUserApi.verify();
// Parse the HTML response to retrieve the serialized redux state.
// We do this here to make sure the sagas are actually run, because the
// API token is retrieved from the cookie on the server, therefore the
// user profile too.
const $ = cheerio.load(response.res.text);
const reduxStoreState = JSON.parse($('#redux-store-state').html());
expect(reduxStoreState.api).toEqual(api);
expect(reduxStoreState.user).toEqual(user);
});
it('it serializes the redux state in html', async () => {
const profile = createUserProfileResponse({ id: 42, username: 'babar' });
mockUserApi
.expects('userProfile')
.once()
.returns(Promise.resolve(profile));
const token = userAuthToken();
const { store, sagaMiddleware } = createStoreAndSagas();
const client = testClient({
store,
sagaMiddleware,
appSagas: userSaga,
});
const response = await client
.get('/en-US/firefox/')
.set('cookie', `${defaultConfig.get('cookieName')}="${token}"`)
.end();
const { api, user } = store.getState();
// Parse the HTML response to retrieve the serialized redux state.
const $ = cheerio.load(response.res.text);
const reduxStoreState = JSON.parse($('#redux-store-state').html());
expect(reduxStoreState.api).toEqual(api);
expect(reduxStoreState.user).toEqual(user);
mockUserApi.verify();
});
});
});