MediaWiki 1.41.2
SpecialJavaScriptTest.php
Go to the documentation of this file.
1<?php
24namespace MediaWiki\Specials;
25
34
39
40 public function __construct() {
41 parent::__construct( 'JavaScriptTest' );
42 }
43
44 public function execute( $par ) {
45 $this->getOutput()->disable();
46
47 if ( $par === 'qunit/export' ) {
48 // Send the JavaScript payload.
49 $this->exportJS();
50 } elseif ( $par === null || $par === '' || $par === 'qunit' || $par === 'qunit/plain' ) {
51 // Render the page
52 // (Support "/qunit" and "/qunit/plain" for backwards-compatibility)
53 $this->renderPage();
54 } else {
55 wfHttpError( 404, 'Unknown action', "Unknown action \"$par\"." );
56 }
57 }
58
64 private function exportJS() {
65 $out = $this->getOutput();
66 $req = $this->getContext()->getRequest();
67 $rl = $out->getResourceLoader();
68
69 // Allow framing (disabling wgBreakFrames). Otherwise, mediawiki.page.ready
70 // will close this tab when running from CLI using karma-qunit.
71 $out->setPreventClickjacking( false );
72
73 $query = [
74 'lang' => 'qqx',
75 'skin' => 'fallback',
76 'debug' => $req->getRawVal( 'debug' ),
77 'target' => 'test',
78 ];
79 $embedContext = new RL\Context( $rl, new FauxRequest( $query ) );
80 $query['only'] = 'scripts';
81 $startupContext = new RL\Context( $rl, new FauxRequest( $query ) );
82
83 $modules = $rl->getTestSuiteModuleNames();
84 $component = $req->getRawVal( 'component' );
85 if ( $component ) {
86 $module = 'test.' . $component;
87 if ( !in_array( 'test.' . $component, $modules ) ) {
89 404,
90 'Unknown test module',
91 "'$module' is not a defined test module. "
92 . 'Register one via the QUnitTestModules attribute in extension.json.'
93 );
94 return;
95 }
96 $modules = [ 'test.' . $component ];
97 }
98
99 // Disable module storage.
100 // The unit test for mw.loader.store will enable it (with a mock timers).
101 $config = new MultiConfig( [
102 new HashConfig( [ MainConfigNames::ResourceLoaderStorageEnabled => false ] ),
103 $rl->getConfig(),
104 ] );
105
106 // Disable autostart because we load modules asynchronously. By default, QUnit would start
107 // at domready when there are no tests loaded and also fire 'QUnit.done' which then instructs
108 // Karma to exit the browser process before the tests even finished loading.
109 $qunitConfig = 'QUnit.config.autostart = false;'
110 . 'if (window.__karma__) {'
111 // karma-qunit's use of autostart=false and QUnit.start conflicts with ours.
112 // Hack around this by replacing 'karma.loaded' with a no-op and perform its duty of calling
113 // `__karma__.start()` ourselves. See <https://github.com/karma-runner/karma-qunit/issues/27>.
114 . 'window.__karma__.loaded = function () {};'
115 . '}';
116
117 // The below is essentially a pure-javascript version of OutputPage::headElement().
118 $startupModule = $rl->getModule( 'startup' );
119 $startupModule->setConfig( $config );
120 $code = $rl->makeModuleResponse( $startupContext, [ 'startup' => $startupModule ] );
121 // The following has to be deferred via RLQ because the startup module is asynchronous.
122 $code .= ResourceLoader::makeLoaderConditionalScript(
123 // Embed page-specific mw.config variables.
124 //
125 // For compatibility with older tests, these will come from the user
126 // action "viewing Special:JavaScripTest".
127 //
128 // This is deprecated since MediaWiki 1.25 and slowly being phased out in favour of:
129 // 1. tests explicitly mocking the configuration they depend on.
130 // 2. tests explicitly skipping or not loading code that is only meant
131 // for real page views (e.g. not loading as dependency, or using a QUnit
132 // conditional).
133 //
134 // See https://phabricator.wikimedia.org/T89434.
135 // Keep a select few that are commonly referenced.
136 ResourceLoader::makeConfigSetScript( [
137 // used by mediawiki.util
138 'wgPageName' => 'Special:Badtitle/JavaScriptTest',
139 // used as input for mw.Title
140 'wgRelevantPageName' => 'Special:Badtitle/JavaScriptTest',
141 ] )
142 // Embed private modules as they're not allowed to be loaded dynamically
143 . $rl->makeModuleResponse( $embedContext, [
144 'user.options' => $rl->getModule( 'user.options' ),
145 ] )
146 // Load all the test modules
147 . Html::encodeJsCall( 'mw.loader.load', [ $modules ] )
148 );
149 $encModules = Html::encodeJsVar( $modules );
150 $code .= ResourceLoader::makeInlineCodeWithModule( 'mediawiki.base', <<<JAVASCRIPT
151 var start = window.__karma__ ? window.__karma__.start : QUnit.start;
152 // Wait for each module individually, so that partial failures wont break the page
153 // completely by rejecting the promise before all/ any modules are loaded.
154 var promises = $encModules.map( function( module ) {
155 return mw.loader.using( module ).promise();
156 } );
157 Promise.allSettled( promises ).then( start );
158 mw.trackSubscribe( 'resourceloader.exception', function ( topic, err ) {
159 // Things like "dependency missing" or "unknown module".
160 // Re-throw so that they are reported as global exceptions by QUnit and Karma.
161 setTimeout( function () {
162 throw err;
163 } );
164 } );
165JAVASCRIPT
166 );
167
168 header( 'Content-Type: text/javascript; charset=utf-8' );
169 header( 'Cache-Control: private, no-cache, must-revalidate' );
170 echo $qunitConfig;
171 echo $code;
172 }
173
174 private function renderPage() {
175 $basePath = $this->getConfig()->get( MainConfigNames::ResourceBasePath );
176 $headHtml = implode( "\n", [
177 Html::linkedScript( "$basePath/resources/lib/qunitjs/qunit.js" ),
178 Html::linkedStyle( "$basePath/resources/lib/qunitjs/qunit.css" ),
179 Html::linkedStyle( "$basePath/resources/src/qunitjs/qunit-local.css" ),
180 ] );
181
182 $introHtml = $this->msg( 'javascripttest-qunit-intro' )
183 ->params( 'https://www.mediawiki.org/wiki/Manual:JavaScript_unit_testing' )
184 ->parseAsBlock();
185
186 $scriptUrl = $this->getPageTitle( 'qunit/export' )->getFullURL( [
187 'debug' => (string)ResourceLoader::inDebugMode(),
188 ] );
189 $script = Html::linkedScript( $scriptUrl );
190
191 header( 'Content-Type: text/html; charset=utf-8' );
192 echo <<<HTML
193<!DOCTYPE html>
194<title>QUnit</title>
195$headHtml
196$introHtml
197<div id="qunit"></div>
198<div id="qunit-fixture"></div>
199$script
200HTML;
201 }
202
203 protected function getGroupName() {
204 return 'other';
205 }
206}
207
211class_alias( SpecialJavaScriptTest::class, 'SpecialJavaScriptTest' );
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
A Config instance which stores all settings as a member variable.
Provides a fallback sequence for Config objects.
This class is a collection of static functions that serve two purposes:
Definition Html.php:57
A class containing constants representing the names of configuration variables.
const ResourceBasePath
Name constant for the ResourceBasePath setting, for use with Config::get()
const ResourceLoaderStorageEnabled
Name constant for the ResourceLoaderStorageEnabled setting, for use with Config::get()
WebRequest clone which takes values from a provided array.
Context object that contains information about the state of a specific ResourceLoader web request.
Definition Context.php:45
ResourceLoader is a loading system for JavaScript and CSS resources.
Parent class for all special pages.
getPageTitle( $subpage=false)
Get a self-referential title object.
getConfig()
Shortcut to get main config object.
getContext()
Gets the context this SpecialPage is executed in.
msg( $key,... $params)
Wrapper around wfMessage that sets the current context.
getOutput()
Get the OutputPage being used for this instance.
execute( $par)
Default execute method Checks user permissions.
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Ge...