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