File size: 45,368 Bytes
1e92f2d |
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 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 |
import { IncomingMessage } from 'http';
import cloneDeep from 'lodash/cloneDeep';
import mockFs from 'mock-fs';
import sections from 'calypso/sections';
jest.mock( 'child_process', () => ( {
execSync: jest.fn(),
} ) );
jest.mock( 'superagent', () => jest.fn() );
jest.mock( '@automattic/calypso-config', () => {
const impl = jest.fn();
impl.isEnabled = jest.fn();
return impl;
} );
jest.mock( 'calypso/server/sanitize', () => jest.fn() );
jest.mock( 'calypso/server/bundler/utils', () => ( {
hashFile: jest.fn( () => 'hash' ),
getUrl: jest.fn( jest.requireActual( 'calypso/server/bundler/utils' ).getUrl ),
} ) );
jest.mock( 'calypso/sections', () => {
// eslint-disable-next-line no-shadow
const sections = jest.requireActual( 'calypso/sections' );
sections
.filter( ( section ) => section.isomorphic )
.forEach( ( section ) => {
section.load = jest.fn( () => ( {
default: jest.fn(),
} ) );
} );
return sections;
} );
jest.mock( 'calypso/sections-filter', () => jest.fn( () => true ) );
jest.mock( 'calypso/login', () => {
const impl = jest.fn();
impl.LOGIN_SECTION_DEFINITION = {
name: 'login',
paths: [ '/log-in' ],
module: 'login',
enableLoggedOut: true,
isomorphic: true,
};
return impl;
} );
jest.mock( 'calypso/server/isomorphic-routing', () => ( {
serverRouter: jest.fn(),
getNormalizedPath: jest.fn(),
getCacheKey: jest.fn(),
} ) );
jest.mock( 'calypso/server/render', () => ( {
serverRender: jest.fn(),
renderJsx: jest.fn(),
attachBuildTimestamp: jest.fn(),
attachHead: jest.fn(),
attachI18n: jest.fn(),
} ) );
jest.mock( 'calypso/server/state-cache', () => new Map() );
jest.mock( 'calypso/server/user-bootstrap', () => jest.fn() );
jest.mock( 'calypso/state', () => ( {
createReduxStore: jest.fn(),
} ) );
jest.mock( 'calypso/state/redux-store', () => ( {
setStore: jest.fn(),
registerReducer: jest.fn(),
} ) );
jest.mock( 'calypso/state/reducer', () => jest.fn() );
jest.mock( 'calypso/state/current-user/actions', () => ( {
setCurrentUser: jest.fn(),
} ) );
jest.mock( 'calypso/lib/paths', () => ( {
login: jest.fn(),
} ) );
jest.mock( './analytics', () => ( {
logSectionResponse: jest.fn(),
} ) );
jest.mock( 'calypso/server/lib/analytics', () => ( {
tracks: {
recordEvent: jest.fn(),
},
} ) );
jest.mock( 'calypso/lib/i18n-utils', () => ( {
getLanguage: jest.fn( ( lang ) => ( { langSlug: lang } ) ),
filterLanguageRevisions: jest.fn(),
} ) );
jest.mock( 'calypso/lib/oauth2-clients', () => ( {
isWooOAuth2Client: jest.fn(),
} ) );
/**
* Builds an app for an specific environment.
*
* This test has a complex setup because the environment. Loading the environment is a side
* effect perform when `../index.js` is imported, so it is tricky to mock. Instead of spreading
* this logic across all tests, we have a builder pattern to load the app.
*
* As it uses isolated registries, any mock set outside this builder won't be visible for the
* built app. That's why we need to require mocks here and expose them via getMocks();
* @param environment the environment
*/
const buildApp = ( environment ) => {
let mocks = {};
const tearDown = [];
let defaultUrl = '/';
const defaultCookies = {};
let userAgent = '';
// We need to restore modules and filesystem so requiring modules inside `isolatedModules` works
mockFs.restore();
jest.resetModules();
// Load the app
let appFactory;
jest.isolateModules( () => {
// When the app requries these modules, they are loaded from its isolated registry.
// Requiring them here will give us the same instance used by the app, this will allow
// us to change the mock implementation later or make assertions about it.
mocks.config = require( '@automattic/calypso-config' );
const {
attachBuildTimestamp,
attachI18n,
attachHead,
renderJsx,
serverRender,
} = require( 'calypso/server/render' );
mocks = { ...mocks, attachBuildTimestamp, attachI18n, attachHead, renderJsx, serverRender };
mocks.sanitize = require( 'calypso/server/sanitize' );
mocks.createReduxStore = require( 'calypso/state' ).createReduxStore;
mocks.execSync = require( 'child_process' ).execSync;
mocks.login = require( 'calypso/lib/paths' ).login;
mocks.getBootstrappedUser = require( 'calypso/server/user-bootstrap' );
mocks.setCurrentUser = require( 'calypso/state/current-user/actions' ).setCurrentUser;
mocks.analytics = require( 'calypso/server/lib/analytics' );
// Set the environment. This has to be done before requiring `../index.js`
mocks.config.mockImplementation(
( key ) =>
( {
hostname: 'valid.hostname',
magnificent_non_en_locales: [ 'ar', 'es' ],
port: 3000,
env_id: environment,
rtl: false,
i18n_default_locale_slug: 'en',
favicon_url: 'http://favicon.url/',
enable_all_sections: true,
} )[ key ]
);
appFactory = require( '../index' ).default;
} );
const app = appFactory();
return {
withUrl( url ) {
defaultUrl = url;
tearDown.push( () => ( defaultUrl = '/' ) );
},
withAuthenticatedUser() {
defaultCookies.wordpress_logged_in = true;
tearDown.push( () => delete defaultCookies.wordpress_logged_in );
},
withAnonymousUser() {
defaultCookies.wordpress_logged_in = false;
tearDown.push( () => delete defaultCookies.wordpress_logged_in );
},
withMockFilesystem() {
const assetsList = [
'/calypso/evergreen/entry-main.1.min.js',
'/calypso/evergreen/entry-main.2.min.js',
'/calypso/evergreen/entry-main.3.min.css',
'/calypso/evergreen/entry-main.4.min.rtl.css',
];
const assets = {
manifests: [
'/* webpack manifest for evergreen */',
'/* webpack runtime for evergreen */',
],
assets: {
'entry-main': assetsList,
'entry-domains-landing': assetsList.map( ( asset ) =>
asset.replace( 'entry-main', 'entry-domains-landing' )
),
'entry-gutenboarding': assetsList.map( ( asset ) =>
asset.replace( 'entry-main', 'entry-gutenboarding' )
),
'entry-browsehappy': assetsList.map( ( asset ) =>
asset.replace( 'entry-main', 'entry-browsehappy' )
),
...Object.fromEntries(
sections.map( ( section ) => [
section.name,
[
`/calypso/evergreen/${ section.name }.js`,
`/calypso/evergreen/${ section.name }.css`,
`/calypso/evergreen/${ section.name }.rtl.css`,
],
] )
),
},
};
mockFs( {
'./build/assets.json': JSON.stringify( assets ),
'./public/languages/lang-revisions.json': JSON.stringify( { es: 1234 } ),
} );
tearDown.push( () => mockFs.restore() );
},
withEvergreenBrowser() {
userAgent =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36';
tearDown.push( () => ( userAgent = '' ) );
return this;
},
withNonEvergreenBrowser() {
userAgent = 'Mozilla/5.0 (Windows NT 10.0; Trident/7.0; rv:11.0) like Gecko';
tearDown.push( () => ( userAgent = '' ) );
return this;
},
withConfigEnabled( enabledOptions ) {
mocks.config.isEnabled.mockImplementation( ( key ) => {
return enabledOptions[ key ];
} );
tearDown.push( () => mocks.config.isEnabled.mockReset() );
},
withMockedVariable( object, name, value ) {
const valueExists = name in object;
const oldValue = object[ name ];
object[ name ] = value;
tearDown.push( () => {
// If there was an old value, restore it. Otherwise delete
// the mocked value. This is required for process.env
if ( valueExists ) {
object[ name ] = oldValue;
} else {
delete object[ name ];
}
} );
},
withRenderJSX( value ) {
mocks.renderJsx.mockImplementation( () => value );
tearDown.push( () => mocks.renderJsx.mockReset() );
},
withFailedRenderJSX( error ) {
mocks.renderJsx.mockImplementation( () => {
throw error;
} );
tearDown.push( () => mocks.renderJsx.mockReset() );
},
withExecCommands( commands ) {
mocks.execSync.mockImplementation( ( command ) => commands[ command ] );
tearDown.push( () => mocks.execSync.mockReset() );
},
withServerRender( output ) {
mocks.serverRender.mockImplementation( ( req, res ) => res.send( output ) );
tearDown.push( () => mocks.serverRender.mockReset() );
},
withBootstrapUser( user ) {
mocks.getBootstrappedUser.mockImplementation( () => Promise.resolve( user ) );
tearDown.push( () => mocks.getBootstrappedUser.mockReset() );
},
withFailedBootstrapUser( error ) {
mocks.getBootstrappedUser.mockImplementation( () => Promise.reject( error ) );
tearDown.push( () => mocks.getBootstrappedUser.mockReset() );
},
withReduxStore( store ) {
mocks.createReduxStore.mockImplementation( () => store );
tearDown.push( () => mocks.createReduxStore.mockReset() );
},
withSetCurrentAction( action ) {
mocks.setCurrentUser.mockImplementation( () => action );
tearDown.push( () => mocks.setCurrentUser.mockReset() );
},
run( { request = {}, response = {} } = {} ) {
return new Promise( ( resolve ) => {
const mockRequest = Object.assign( new IncomingMessage(), {
body: {},
cookies: defaultCookies,
query: {},
params: {},
// Setup by parent app using 'express-useragent'
useragent: {
source: '',
},
headers: {
'user-agent': userAgent,
},
url: defaultUrl,
method: 'GET',
get: jest.fn(),
socket: {},
logger: {
error: jest.fn(),
},
...request,
} );
// Using cloneDeep to capture the state of the request/response objects right now, in case
// an async middleware changes them _after_ the request handler has been executed
const mockResponse = {
setHeader: jest.fn(),
getHeader: jest.fn(),
clearCookie: jest.fn(),
send: jest.fn( () => {
resolve( {
request: cloneDeep( mockRequest ),
response: cloneDeep( mockResponse ),
} );
} ),
end: jest.fn( () => {
resolve( {
request: cloneDeep( mockRequest ),
response: cloneDeep( mockResponse ),
} );
} ),
redirect: jest.fn( () => {
resolve( {
request: cloneDeep( mockRequest ),
response: cloneDeep( mockResponse ),
} );
} ),
...response,
};
app( mockRequest, mockResponse );
} );
},
getMocks() {
return mocks;
},
reset() {
tearDown.forEach( ( method ) => method() );
tearDown.length = 0;
},
};
};
const assertDefaultContext = ( { url, entry } ) => {
let app;
beforeAll( () => {
// Building an app is expensive, so we build it once here and set its mocks before each test.
app = buildApp( 'production' );
} );
beforeEach( () => {
app.withUrl( url );
app.withConfigEnabled( { 'use-translation-chunks': true } );
app.withServerRender( '' );
app.withMockFilesystem();
app.withEvergreenBrowser();
} );
afterEach( () => {
app.reset();
} );
it( 'sets the commit sha using the value from COMMIT_SHA', async () => {
app.withMockedVariable( process.env, 'COMMIT_SHA', 'abcabc' );
const { request } = await app.run();
expect( request.context.commitSha ).toBe( 'abcabc' );
} );
it( 'sets the commit sha to "(unknown)"', async () => {
const { request } = await app.run();
expect( request.context.commitSha ).toBe( '(unknown)' );
} );
it( 'sets the debug mode for the compiler', async () => {
const { request } = await app.run();
expect( request.context.compileDebug ).toBe( false );
} );
it( 'sets the user to false', async () => {
const { request } = await app.run();
expect( request.context.user ).toBe( false );
} );
it( 'sets the environment', async () => {
const { request } = await app.run();
expect( request.context.env ).toBe( 'production' );
} );
it( 'sets the sanitize method', async () => {
const { request } = await app.run();
expect( request.context.sanitize ).toEqual( app.getMocks().sanitize );
} );
it( 'sets lang to the default', async () => {
const { request } = await app.run();
expect( request.context.lang ).toEqual( 'en' );
} );
if ( entry ) {
it( 'sets the entrypoint', async () => {
const { request } = await app.run();
expect( request.context.entrypoint ).toEqual( {
js: [ `/calypso/evergreen/${ entry }.1.min.js`, `/calypso/evergreen/${ entry }.2.min.js` ],
'css.ltr': [ `/calypso/evergreen/${ entry }.3.min.css` ],
'css.rtl': [ `/calypso/evergreen/${ entry }.4.min.rtl.css` ],
} );
} );
}
it( 'sets the manifest', async () => {
const { request } = await app.run();
expect( request.context.manifests ).toEqual( [
'/* webpack manifest for evergreen */',
'/* webpack runtime for evergreen */',
] );
} );
it( 'sets the featuresHelper when config is enabled', async () => {
app.withConfigEnabled( { 'dev/features-helper': true } );
const { request } = await app.run();
expect( request.context.featuresHelper ).toEqual( true );
} );
it( 'sets the featuresHelper when config is disabled', async () => {
app.withConfigEnabled( { 'dev/features-helper': false } );
const { request } = await app.run();
expect( request.context.featuresHelper ).toEqual( false );
} );
it( 'sets devDocsUrl', async () => {
const { request } = await app.run();
expect( request.context.devDocsURL ).toEqual( '/devdocs' );
} );
it( 'sets redux store', async () => {
const theStore = {};
app.withReduxStore( theStore );
const { request } = await app.run();
expect( request.context.store ).toEqual( theStore );
} );
describe( 'sets the target in production mode', () => {
beforeEach( () => {
app.withMockedVariable( process.env, 'NODE_ENV', 'production' );
} );
it( 'serves evergreen for all browsers', async () => {
const { request } = await app.run();
expect( request.context.target ).toEqual( 'evergreen' );
} );
} );
it( 'translations chunks can be disabled', async () => {
app.withConfigEnabled( { 'use-translation-chunks': false } );
const { request } = await app.run();
expect( request.context.useTranslationChunks ).toEqual( false );
} );
it( 'uses translations chunks when enabled in the config', async () => {
app.withConfigEnabled( { 'use-translation-chunks': true } );
const { request } = await app.run();
expect( request.context.useTranslationChunks ).toEqual( true );
} );
it( 'uses translations chunks when enabled in the request flags', async () => {
const { request } = await app.run( { query: { flags: 'use-translation-chunks' } } );
expect( request.context.useTranslationChunks ).toEqual( true );
} );
it( 'uses translations chunks when specified in the request', async () => {
const { request } = await app.run( { query: { useTranslationChunks: true } } );
expect( request.context.useTranslationChunks ).toEqual( true );
} );
it( 'sets the client ip', async () => {
const { request } = await app.run( { request: { ip: '192.168.0.1' } } );
expect( request.context.app.clientIp ).toEqual( '192.168.0.1' );
} );
it( 'sets the client ip replacing the ipv6 prefix for ipv4 addresses', async () => {
const { request } = await app.run( { request: { ip: '::ffff:192.168.0.1' } } );
expect( request.context.app.clientIp ).toEqual( '192.168.0.1' );
} );
it( 'debug mode is disabled by default', async () => {
const { request } = await app.run();
expect( request.context.app.isDebug ).toEqual( false );
} );
it( 'debug mode is enabled if the query parameter is present', async () => {
const { request } = await app.run( { request: { query: { debug: true } } } );
expect( request.context.app.isDebug ).toEqual( true );
} );
it( 'debug mode is enabled for development environment', async () => {
const customApp = buildApp( 'development' );
customApp.withServerRender( '' );
customApp.withMockFilesystem();
customApp.withEvergreenBrowser();
const { request } = await customApp.run();
expect( request.context.app.isDebug ).toEqual( true );
} );
it( 'debug mode is enabled for jetpack-cloud-development environment', async () => {
const customApp = buildApp( 'jetpack-cloud-development' );
customApp.withServerRender( '' );
customApp.withMockFilesystem();
customApp.withEvergreenBrowser();
const { request } = await customApp.run();
expect( request.context.app.isDebug ).toEqual( true );
} );
describe( 'with environment wpcalypso', () => {
let customApp;
beforeAll( () => {
customApp = buildApp( 'wpcalypso' );
} );
beforeEach( () => {
customApp.withServerRender( '' );
customApp.withMockFilesystem();
customApp.withEvergreenBrowser();
} );
afterEach( () => {
customApp.reset();
} );
it( 'sets the badge', async () => {
const { request } = await customApp.run();
expect( request.context.badge ).toEqual( 'wpcalypso' );
} );
it( 'sets devDocs', async () => {
const { request } = await customApp.run();
expect( request.context.devDocs ).toEqual( true );
} );
it( 'sets the feedback url', async () => {
const { request } = await customApp.run();
expect( request.context.feedbackURL ).toEqual(
'https://github.com/Automattic/wp-calypso/issues/'
);
} );
it( 'sets the branch name', async () => {
const { request } = await customApp.run( {
request: { query: { branch: 'my-branch' } },
} );
expect( request.context.branchName ).toEqual( 'my-branch' );
} );
} );
describe( 'with environment horizon', () => {
let customApp;
beforeAll( () => {
customApp = buildApp( 'horizon' );
} );
beforeEach( () => {
customApp.withServerRender( '' );
customApp.withMockFilesystem();
customApp.withEvergreenBrowser();
} );
afterEach( () => {
customApp.reset();
} );
it( 'sets the badge', async () => {
const { request } = await customApp.run();
expect( request.context.badge ).toEqual( 'feedback' );
} );
it( 'sets the feedback url', async () => {
const { request } = await customApp.run();
expect( request.context.feedbackURL ).toEqual( 'https://horizonfeedback.wordpress.com/' );
} );
} );
describe( 'with environment stage', () => {
let customApp;
beforeAll( () => {
customApp = buildApp( 'stage' );
} );
beforeEach( () => {
customApp.withServerRender( '' );
customApp.withMockFilesystem();
customApp.withEvergreenBrowser();
} );
afterEach( () => {
customApp.reset();
} );
it( 'sets the badge', async () => {
const { request } = await customApp.run();
expect( request.context.badge ).toEqual( 'staging' );
} );
it( 'sets the feedback url', async () => {
const { request } = await customApp.run();
expect( request.context.feedbackURL ).toEqual(
'https://github.com/Automattic/wp-calypso/issues/'
);
} );
} );
describe( 'with environment development', () => {
let customApp;
beforeAll( () => {
customApp = buildApp( 'development' );
} );
beforeEach( () => {
customApp.withServerRender( '' );
customApp.withMockFilesystem();
customApp.withEvergreenBrowser();
customApp.withExecCommands( {
'git rev-parse --abbrev-ref HEAD': 'my-branch',
'git rev-parse --short HEAD': 'abcd0123',
} );
} );
afterEach( () => {
customApp.reset();
} );
it( 'sets the badge', async () => {
const { request } = await customApp.run();
expect( request.context.badge ).toEqual( 'dev' );
} );
it( 'sets devDocs', async () => {
const { request } = await customApp.run();
expect( request.context.devDocs ).toEqual( true );
} );
it( 'sets the feedback url', async () => {
const { request } = await customApp.run();
expect( request.context.feedbackURL ).toEqual(
'https://github.com/Automattic/wp-calypso/issues/'
);
} );
it( 'sets the branch name', async () => {
const { request } = await customApp.run();
expect( request.context.branchName ).toEqual( 'my-branch' );
} );
it( 'sets the commit checksum', async () => {
const { request } = await customApp.run();
expect( request.context.commitChecksum ).toEqual( 'abcd0123' );
} );
} );
describe( 'with environment jetpack-cloud-stage', () => {
let customApp;
beforeAll( () => {
customApp = buildApp( 'jetpack-cloud-stage' );
} );
beforeEach( () => {
customApp.withServerRender( '' );
customApp.withMockFilesystem();
customApp.withEvergreenBrowser();
} );
afterEach( () => {
customApp.reset();
} );
it( 'sets the badge', async () => {
const { request } = await customApp.run();
expect( request.context.badge ).toEqual( 'jetpack-cloud-staging' );
} );
it( 'sets the feedback url', async () => {
const { request } = await customApp.run();
expect( request.context.feedbackURL ).toEqual(
'https://github.com/Automattic/wp-calypso/issues/'
);
} );
} );
describe( 'with environment jetpack-cloud-development', () => {
let customApp;
beforeAll( () => {
customApp = buildApp( 'jetpack-cloud-development' );
} );
beforeEach( () => {
customApp.withServerRender( '' );
customApp.withMockFilesystem();
customApp.withEvergreenBrowser();
customApp.withExecCommands( {
'git rev-parse --abbrev-ref HEAD': 'my-branch',
'git rev-parse --short HEAD': 'abcd0123',
} );
} );
afterEach( () => {
customApp.reset();
} );
it( 'sets the badge', async () => {
const { request } = await customApp.run();
expect( request.context.badge ).toEqual( 'jetpack-cloud-dev' );
} );
it( 'sets the feedback url', async () => {
const { request } = await customApp.run();
expect( request.context.feedbackURL ).toEqual(
'https://github.com/Automattic/wp-calypso/issues/'
);
} );
it( 'sets the branch name', async () => {
const { request } = await customApp.run();
expect( request.context.branchName ).toEqual( 'my-branch' );
} );
it( 'sets the commit checksum', async () => {
const { request } = await customApp.run();
expect( request.context.commitChecksum ).toEqual( 'abcd0123' );
} );
} );
};
const assertSection = ( { url, entry, sectionName, sectionGroup } ) => {
let app;
beforeAll( () => {
// Building an app is expensive, so we build it once here and set its mocks before each test.
app = buildApp( 'production' );
} );
beforeEach( () => {
app.withUrl( url );
app.withConfigEnabled( { 'use-translation-chunks': true } );
app.withServerRender( '' );
app.withMockFilesystem();
app.withEvergreenBrowser();
} );
afterEach( () => {
app.reset();
} );
it( `handles path ${ url } with section "${ sectionName }"`, async () => {
const { request } = await app.run();
expect( request.context.sectionName ).toBe( sectionName );
} );
it( 'captures the group of the section', async () => {
const { request } = await app.run();
expect( request.context.sectionGroup ).toBe( sectionGroup );
} );
if ( entry ) {
it( 'do not set chunkFiles for sections with associated entrypoints for evergreen browsers', async () => {
const { request } = await app.withEvergreenBrowser().run();
expect( request.context.chunkFiles ).toEqual( {
'css.ltr': [],
'css.rtl': [],
js: [],
} );
} );
} else {
it( 'sets chunkFiles for evergreen browsers', async () => {
const { request } = await app.withEvergreenBrowser().run();
expect( request.context.chunkFiles ).toEqual( {
'css.ltr': [ `/calypso/evergreen/${ sectionName }.css` ],
'css.rtl': [ `/calypso/evergreen/${ sectionName }.rtl.css` ],
js: [ `/calypso/evergreen/${ sectionName }.js` ],
} );
} );
}
it( 'renders the section', async () => {
app.withServerRender( 'output' );
const { response } = await app.run();
expect( response.statusCode ).toBe( 200 );
expect( response.send ).toHaveBeenCalledWith( 'output' );
} );
describe( 'for authenticated users', () => {
let theStore;
let theAction;
beforeEach( () => {
theStore = {
dispatch: jest.fn(),
};
theAction = {};
// This method resets the existing enabled config, we need to re-enable 'use-translation-chunks'.
app.withAuthenticatedUser();
app.withConfigEnabled( {
'wpcom-user-bootstrap': true,
'use-translation-chunks': true,
} );
app.withBootstrapUser( {} );
app.withReduxStore( theStore );
app.withSetCurrentAction( theAction );
} );
it( 'sets frame options', async () => {
const { response } = await app.run();
expect( response.setHeader ).toHaveBeenCalledWith( 'X-Frame-Options', 'SAMEORIGIN' );
} );
it( 'sets language revisions for evergreen browsers', async () => {
app.withEvergreenBrowser();
const { request } = await app.run();
expect( request.context.languageRevisions ).toEqual( { es: 1234 } );
} );
it( 'gets the redirect url for https requests', async () => {
await app.run( {
request: {
get: jest.fn( ( header ) => ( header === 'X-Forwarded-Proto' ? 'https' : undefined ) ),
},
} );
expect( app.getMocks().login ).toHaveBeenCalledWith( {
redirectTo: `https://valid.hostname${ url }`,
} );
} );
it( 'gets the redirect url for http requests', async () => {
await app.run( {
request: {
get: jest.fn( ( header ) => ( header === 'X-Forwarded-Proto' ? 'http' : undefined ) ),
},
} );
expect( app.getMocks().login ).toHaveBeenCalledWith( {
redirectTo: `http://valid.hostname${ url }`,
} );
} );
it( 'saves the user in the context', async () => {
const theUser = {};
app.withBootstrapUser( theUser );
const { request } = await app.run();
expect( request.context.user ).toEqual( theUser );
} );
it( 'sets the locale in the store', async () => {
const theUser = {
localeSlug: 'es',
localeVariant: 'ES',
};
app.withBootstrapUser( theUser );
const { request } = await app.run();
expect( request.context.lang ).toEqual( 'es' );
expect( theStore.dispatch ).toHaveBeenCalledWith( {
type: 'LOCALE_SET',
localeSlug: 'es',
localeVariant: 'ES',
} );
} );
it( 'redirects the user if public API authorization is required', () =>
// eslint-disable-next-line no-async-promise-executor
new Promise( async ( done ) => {
app.withFailedBootstrapUser( { error: 'authorization_required' } );
app.getMocks().login.mockImplementation( ( { redirectTo } ) => redirectTo );
// Even after the redirect, it will log the error. Silence the error output to make Jest happy.
jest.spyOn( console, 'error' ).mockImplementation( () => {} );
const { response } = await app.run();
expect( response.redirect ).toHaveBeenCalledWith( `http://valid.hostname${ url }` );
// The redirects abive will leave the promise in `setUpLocalLanguageRevisions()`
// pending, and because we are mocking the filesystem, it will fail when we tear down the
// test and output something to the console. Jest will detect it and show an error because
// you are not supossed to log anything after the test is done.
//
// This timer should give time to that promise to fail within the test.
setTimeout( done, 5 );
} ) );
} );
describe( 'for anonymous users', () => {
beforeEach( () => {
app.withAnonymousUser();
} );
it( 'sets frame options', async () => {
const { response } = await app.run();
expect( response.setHeader ).toHaveBeenCalledWith( 'X-Frame-Options', 'SAMEORIGIN' );
} );
it( 'sets language revisions for evergreen browsers', async () => {
app.withEvergreenBrowser();
const { request } = await app.run();
expect( request.context.languageRevisions ).toEqual( { es: 1234 } );
} );
} );
describe( 'default context', () => {
assertDefaultContext( { url, entry } );
} );
};
describe( 'main app', () => {
let app;
beforeAll( () => {
// Building an app is expensive, so we build it once here and set its mocks before each test.
app = buildApp( 'production' );
} );
beforeEach( () => {
app.withConfigEnabled( { 'use-translation-chunks': true } );
app.withServerRender( '' );
app.withMockFilesystem();
app.withEvergreenBrowser();
} );
afterEach( async () => {
jest.clearAllMocks();
app.reset();
} );
describe( 'Middleware loggedInContext', () => {
it( 'detects if it is a support session based on a header', async () => {
const { request } = await app.run( {
request: { get: jest.fn( ( header ) => header === 'x-support-session' ) },
} );
expect( request.context.isSupportSession ).toBe( true );
} );
it( 'detects if it is a support session based on a cookie', async () => {
const { request } = await app.run( { request: { cookies: { support_session_id: true } } } );
expect( request.context.isSupportSession ).toBe( true );
} );
it( 'detects if it is logged in based on a cookie', async () => {
const { request } = await app.run( { request: { cookies: { wordpress_logged_in: true } } } );
expect( request.context.isLoggedIn ).toBe( true );
} );
} );
describe( 'Route /sites/:site/:section', () => {
[
{ section: 'posts', url: '/posts/my-site' },
{ section: 'pages', url: '/pages/my-site' },
{ section: 'sharing', url: '/sharing/my-site' },
{ section: 'upgrade', url: '/upgrade/my-site' },
{ section: 'checkout', url: '/checkout/my-site' },
{ section: 'change-theme', url: '/themes' },
].forEach( ( { section, url } ) => {
it( `Redirects from old newdash format (section ${ section })`, async () => {
const { response } = await app.run( { request: { url: `/sites/my-site/${ section }` } } );
expect( response.redirect ).toHaveBeenCalledWith( url );
} );
} );
} );
describe( 'Route /plans', () => {
it( 'redirects to login if the request is for jetpack', async () => {
const { response } = await app.run( {
request: { url: '/plans', query: { for: 'jetpack' } },
} );
expect( response.redirect ).toHaveBeenCalledWith(
'https://wordpress.com/wp-login.php?redirect_to=https%3A%2F%2Fwordpress.com%2Fplans'
);
} );
it( 'redirects to public pricing page with coupon and ref params', async () => {
app.withConfigEnabled( {
'jetpack-cloud/connect': false,
} );
const { response } = await app.run( {
request: { url: '/plans', query: { ref: 'test', coupon: 'test' } },
} );
expect( response.redirect ).toHaveBeenCalledWith(
'https://wordpress.com/pricing/?ref=test&coupon=test'
);
} );
} );
describe( 'Route /menus', () => {
it( 'redirects to menus when there is a site', async () => {
const { response } = await app.run( { request: { url: '/menus/my-site' } } );
expect( response.redirect ).toHaveBeenCalledWith( 301, '/customize/menus/my-site' );
} );
it( 'redirects to menus when there is not a site', async () => {
const { response } = await app.run( { request: { url: '/menus' } } );
expect( response.redirect ).toHaveBeenCalledWith( 301, '/customize/menus/' );
} );
} );
describe( 'Route /domains', () => {
it( 'redirects from /domains to /start/domain', async () => {
const { response } = await app.run( { request: { url: '/domains' } } );
expect( response.redirect ).toHaveBeenCalledWith( '/start/domain' );
} );
it( 'redirects from /domains to /start/domain with selected domain', async () => {
const { response } = await app.run( {
request: { url: '/domains', query: { new: 'my-domain.com' } },
} );
expect( response.redirect ).toHaveBeenCalledWith( '/start/domain?new=my-domain.com' );
} );
it( 'redirects from /start/domain-first to /start/domain', async () => {
const { response } = await app.run( { request: { url: '/start/domain-first' } } );
expect( response.redirect ).toHaveBeenCalledWith( '/start/domain' );
} );
it( 'redirects from /start/domain-first to /start/domain with selected domain', async () => {
const { response } = await app.run( {
request: { url: '/start/domain-first', query: { new: 'my-domain.com' } },
} );
expect( response.redirect ).toHaveBeenCalledWith( '/start/domain?new=my-domain.com' );
} );
} );
describe( 'Route /domain-services/:action', () => {
it( 'attaches info to the context form server/render', async () => {
const { attachBuildTimestamp, attachI18n, attachHead } = app.getMocks();
await app.run( { request: { url: '/domain-services/renovate' } } );
expect( attachBuildTimestamp ).toHaveBeenCalled();
expect( attachI18n ).toHaveBeenCalled();
expect( attachHead ).toHaveBeenCalled();
} );
it( 'adds clientData to the context', async () => {
app.getMocks().config.clientData = { client: 'data' };
const { request } = await app.run( { request: { url: '/domain-services/renovate' } } );
expect( request.context.clientData ).toEqual( { client: 'data' } );
} );
it( 'adds domainsLandingData to the context', async () => {
const { request } = await app.run( {
request: { url: '/domain-services/renovate', query: { domain: 'test' } },
} );
expect( request.context.domainsLandingData ).toEqual( {
action: 'renovate',
query: {
domain: 'test',
},
} );
} );
it( 'renders domains-landing page', async () => {
app.withRenderJSX( '<div>page</div>' );
const { renderJsx } = app.getMocks();
const { response } = await app.run( {
request: { url: '/domain-services/renovate', query: { domain: 'test' } },
} );
expect( renderJsx ).toHaveBeenCalledWith(
'domains-landing',
expect.objectContaining( {
domainsLandingData: {
action: 'renovate',
query: {
domain: 'test',
},
},
} )
);
expect( response.send ).toHaveBeenCalledWith( '<div>page</div>' );
} );
describe( 'default context', () => {
assertDefaultContext( {
url: '/domain-services/renovate',
entry: 'entry-domains-landing',
} );
} );
} );
describe( `Route /home`, () => {
assertSection( {
url: '/home',
sectionName: 'home',
sectionGroup: 'sites',
} );
} );
describe( `Route /sites`, () => {
assertSection( {
url: '/sites',
sectionName: 'sites-dashboard',
sectionGroup: 'sites-dashboard',
} );
} );
describe( `Route /`, () => {
assertSection( {
url: '/',
sectionName: 'root',
sectionGroup: 'root',
} );
describe( 'redirects', () => {
beforeEach( () => {
app.withConfigEnabled( {
'wpcom-user-bootstrap': true,
'use-translation-chunks': true,
} );
app.withBootstrapUser( {} );
app.withReduxStore( {
dispatch: jest.fn(),
} );
} );
afterEach(
() =>
new Promise( ( done ) => {
// The redirects in this section will leave the promise in `setUpLocalLanguageRevisions()`
// pending, and because we are mocking the filesystem, it will fail when we tear down the
// test and output something to the console. Jest will detect it and show an error because
// you are not supossed to log anything after the test is done.
//
// This timer should give time to that promise to fail within the test.
setTimeout( done, 5 );
} )
);
it( 'redirects to stats if reader is disabled', async () => {
app.withConfigEnabled( { reader: false, stats: true } );
const { response } = await app.run( { request: { url: '/' } } );
expect( response.redirect ).toHaveBeenCalledWith( '/stats' );
} );
it( 'redirects to search when passing "s" as the query', async () => {
// eslint-disable-next-line no-async-promise-executor
const { response } = await app.run( {
request: {
url: '/',
cookies: { wordpress_logged_in: true },
query: { s: 'my search' },
},
} );
expect( response.redirect ).toHaveBeenCalledWith(
'https://wordpress.com/reader/search?q=my%20search'
);
} );
it( 'redirects to search when passing "q" as the query', async () => {
// eslint-disable-next-line no-async-promise-executor
const { response } = await app.run( {
request: {
url: '/',
cookies: { wordpress_logged_in: true },
query: { q: 'my search' },
},
} );
expect( response.redirect ).toHaveBeenCalledWith(
'https://wordpress.com/reader/search?q=my%20search'
);
} );
it( 'redirects to legacy email verification when passing "newuseremail" as the query', async () => {
// eslint-disable-next-line no-async-promise-executor
const { response } = await app.run( {
request: {
url: '/',
cookies: { wordpress_logged_in: true },
query: { newuseremail: 'any value' },
},
} );
expect( response.redirect ).toHaveBeenCalledWith(
'https://wordpress.com/verify-email/?newuseremail=any%20value'
);
} );
it( 'redirects to legacy accept invite when passing "wpcom-invite-users" in the query', async () => {
// eslint-disable-next-line no-async-promise-executor
const { response } = await app.run( {
request: {
url: '/',
cookies: { wordpress_logged_in: true },
query: { action: 'wpcom-invite-users' },
},
} );
expect( response.redirect ).toHaveBeenCalledWith(
'https://wordpress.com/accept-invite/?action=wpcom-invite-users'
);
} );
} );
} );
describe( `Route deprecated /new`, () => {
it( 'redirects to start flow', async () => {
const { response } = await app.run( { request: { url: '/new' } } );
expect( response.redirect ).toHaveBeenCalledWith( 301, '/start' );
} );
it( 'redirects to start flow with locale', async () => {
const { response } = await app.run( { request: { url: '/new/fr' } } );
expect( response.redirect ).toHaveBeenCalledWith( 301, '/start/fr' );
} );
} );
describe( 'Route /start/domain-transfer', () => {
it( 'redirects to /setup/domain-transfer', async () => {
const { response } = await app.run( { request: { url: '/start/domain-transfer' } } );
expect( response.redirect ).toHaveBeenCalledWith( 301, '/setup/domain-transfer' );
} );
} );
describe( 'Route /cspreport', () => {
let customApp;
beforeAll( () => {
customApp = buildApp( 'production' );
} );
beforeEach( () => {
customApp.withServerRender( '' );
customApp.withMockFilesystem();
} );
afterEach( () => {
customApp.reset();
} );
it( 'records the event when there is a report', async () => {
const { response, request } = await app.run( {
request: {
method: 'POST',
url: '/cspreport',
body: {
'csp-report': {
'document-uri': 'https://example.com/foo/bar',
referrer: 'https://example.com/',
'violated-directive': 'default-src self',
'original-policy': 'default-src self; report-uri /cspreport',
'blocked-uri': 'http://evilhackerscripts.com',
},
},
},
} );
expect( response.statusCode ).toBe( 200 );
expect( app.getMocks().analytics.tracks.recordEvent ).toHaveBeenCalledWith(
'calypso_csp_report',
{
document_uri: 'https://example.com/foo/bar',
referrer: 'https://example.com/',
violated_directive: 'default-src self',
original_policy: 'default-src self; report-uri /cspreport',
blocked_uri: 'http://evilhackerscripts.com',
},
request
);
} );
it( "returns an error when the report can't be parsed or sent", async () => {
app.getMocks().analytics.tracks.recordEvent.mockImplementation( () => {
throw new Error( 'Fake error' );
} );
const { response } = await app.run( { request: { method: 'POST', url: '/cspreport' } } );
expect( response.statusCode ).toBe( 500 );
} );
} );
describe( 'Route /browsehappy', () => {
beforeEach( () => {
app.withRenderJSX( 'content' );
} );
it( 'renders the content', async () => {
const { response, request } = await app.run( { request: { url: '/browsehappy' } } );
expect( app.getMocks().renderJsx ).toHaveBeenCalledWith( 'browsehappy', request.context );
expect( response.send ).toHaveBeenCalledWith( 'content' );
} );
} );
describe( 'Route /support-user', () => {
beforeEach( () => {
app.withRenderJSX( 'content' );
app.withConfigEnabled( { 'wpcom-user-bootstrap': true } );
} );
it( 'disables iframe', async () => {
const { response } = await app.run( { request: { url: '/support-user' } } );
expect( response.setHeader ).toHaveBeenCalledWith( 'X-Frame-Options', 'DENY' );
} );
it( 'renders unauthorized page if wpcom-user-bootstrap is disabled', async () => {
app.withConfigEnabled( { 'wpcom-user-bootstrap': false } );
const { response } = await app.run( {
request: { url: '/support-user', cookies: { wordpress_logged_in: true } },
} );
expect( app.getMocks().renderJsx ).toHaveBeenCalledWith( 'support-user' );
expect( response.send ).toHaveBeenCalledWith( 'content' );
} );
it( 'renders unauthorized page for anonymous users', async () => {
const { response } = await app.run( { request: { url: '/support-user' } } );
expect( app.getMocks().renderJsx ).toHaveBeenCalledWith( 'support-user' );
expect( response.send ).toHaveBeenCalledWith( 'content' );
} );
it( 'renders unauthorized page for users without flag calypso_support_user', async () => {
app.withBootstrapUser( { meta: { data: { flags: { active_flags: [] } } } } );
const { response } = await app.run( {
request: { url: '/support-user', cookies: { wordpress_logged_in: true } },
} );
expect( app.getMocks().renderJsx ).toHaveBeenCalledWith( 'support-user' );
expect( response.send ).toHaveBeenCalledWith( 'content' );
} );
it( 'renders unauthorized page if there is an error bootstrapping the user', async () => {
app.withFailedBootstrapUser( new Error( 'fake error' ) );
const { response } = await app.run( {
request: { url: '/support-user', cookies: { wordpress_logged_in: true } },
} );
expect( app.getMocks().renderJsx ).toHaveBeenCalledWith( 'support-user' );
expect( response.send ).toHaveBeenCalledWith( 'content' );
expect( response.clearCookie ).toHaveBeenCalledWith( 'wordpress_logged_in', {
path: '/',
httpOnly: true,
domain: '.wordpress.com',
} );
} );
it( 'renders authorized page in development mode', async () => {
const customApp = buildApp( 'development' );
customApp.withRenderJSX( 'content' );
customApp.withEvergreenBrowser();
customApp.withMockFilesystem();
const { response } = await customApp.run( {
request: {
url: '/support-user',
query: {
support_user: 'user',
_support_token: 'token',
support_path: 'path',
},
},
} );
expect( customApp.getMocks().renderJsx ).toHaveBeenCalledWith( 'support-user', {
authorized: true,
supportPath: 'path',
supportToken: 'token',
supportUser: 'user',
} );
expect( response.send ).toHaveBeenCalledWith( 'content' );
} );
it( 'renders authorized page for users with flag calypso_support_user', async () => {
app.withBootstrapUser( {
meta: { data: { flags: { active_flags: [ 'calypso_support_user' ] } } },
} );
const { response } = await app.run( {
request: {
url: '/support-user',
cookies: { wordpress_logged_in: true },
query: {
support_user: 'user',
_support_token: 'token',
support_path: 'path',
},
},
} );
expect( app.getMocks().renderJsx ).toHaveBeenCalledWith( 'support-user', {
authorized: true,
supportPath: 'path',
supportToken: 'token',
supportUser: 'user',
} );
expect( response.send ).toHaveBeenCalledWith( 'content' );
} );
} );
describe( '404 page', () => {
it( 'returns a 404', async () => {
app.withRenderJSX( 'content' );
const { response } = await app.run( { request: { url: '/does-not-exists' } } );
expect( response.send ).toHaveBeenCalledWith( 'content' );
expect( response.statusCode ).toBe( 404 );
expect( app.getMocks().renderJsx ).toHaveBeenCalledWith( '404', {
entrypoint: {
'css.ltr': [ '/calypso/evergreen/entry-main.3.min.css' ],
'css.rtl': [ '/calypso/evergreen/entry-main.4.min.rtl.css' ],
js: [
'/calypso/evergreen/entry-main.1.min.js',
'/calypso/evergreen/entry-main.2.min.js',
],
},
} );
} );
} );
describe( 'Error page', () => {
const forceError = () => {
// response.redirect throwing is very unlikely, but it offers the best
// place to simulate an error in the current implementation of the app
return app.run( {
response: {
redirect: jest.fn( () => {
throw { error: 'fake error' };
} ),
},
} );
};
beforeEach( () => {
app.withConfigEnabled( {
'wpcom-user-bootstrap': true,
'use-translation-chunks': true,
reader: false,
stats: true,
} );
app.withRenderJSX( 'content' );
app.withUrl( '/' );
jest.spyOn( console, 'error' ).mockImplementation( () => {} );
} );
it( 'returns a 500', async () => {
const { response } = await forceError();
expect( response.send ).toHaveBeenCalledWith( 'content' );
expect( response.statusCode ).toBe( 500 );
expect( app.getMocks().renderJsx ).toHaveBeenCalledWith( '500', {
entrypoint: {
'css.ltr': [ '/calypso/evergreen/entry-main.3.min.css' ],
'css.rtl': [ '/calypso/evergreen/entry-main.4.min.rtl.css' ],
js: [
'/calypso/evergreen/entry-main.1.min.js',
'/calypso/evergreen/entry-main.2.min.js',
],
},
} );
} );
it( 'logs the error in development mode', async () => {
const { request } = await forceError();
expect( request.logger.error ).toHaveBeenCalledWith( { error: 'fake error' } );
} );
} );
} );
|