| 1 | QUnit.module( 'mediawiki.ForeignRest', ( hooks ) => { |
| 2 | const CoreForeignApi = require( 'mediawiki.ForeignApi.core' ).ForeignApi; |
| 3 | const CoreForeignRest = require( 'mediawiki.ForeignApi.core' ).ForeignRest; |
| 4 | |
| 5 | hooks.beforeEach( function () { |
| 6 | this.server = this.sandbox.useFakeServer(); |
| 7 | this.server.respondImmediately = true; |
| 8 | this.actionApi = new CoreForeignApi( 'http://test.example.com/api.php' ); |
| 9 | } ); |
| 10 | |
| 11 | QUnit.test( 'get()', function ( assert ) { |
| 12 | const api = new CoreForeignRest( 'http://test.example.com/rest.php', this.actionApi ); |
| 13 | |
| 14 | this.server.respond( ( request ) => { |
| 15 | assert.strictEqual( request.method, 'GET' ); |
| 16 | assert.strictEqual( request.url, 'http://test.example.com/rest.php/test/rest/path' ); |
| 17 | request.respond( 200, { 'Content-Type': 'application/json' }, '{}' ); |
| 18 | } ); |
| 19 | |
| 20 | return api.get( '/test/rest/path' ).then( ( data ) => { |
| 21 | assert.deepEqual( data, {}, 'If request succeeds without errors, resolve deferred' ); |
| 22 | } ); |
| 23 | } ); |
| 24 | |
| 25 | QUnit.test( 'post()', function ( assert ) { |
| 26 | const api = new CoreForeignRest( 'http://test.example.com/rest.php', this.actionApi ); |
| 27 | |
| 28 | this.server.respond( ( request ) => { |
| 29 | assert.strictEqual( request.method, 'POST', 'Method should be POST' ); |
| 30 | assert.strictEqual( request.url, 'http://test.example.com/rest.php/test/bla/bla/bla', 'Url should be correct' ); |
| 31 | assert.true( /^application\/json/.test( request.requestHeaders[ 'Content-Type' ] ), 'Should set JSON content-type' ); |
| 32 | assert.strictEqual( request.requestHeaders.authorization, 'my_token', 'Should pass request header' ); |
| 33 | assert.deepEqual( JSON.parse( request.requestBody ), { param: 'value' }, 'Body should be correct' ); |
| 34 | request.respond( 201, { 'Content-Type': 'application/json' }, '{}' ); |
| 35 | } ); |
| 36 | |
| 37 | return api.post( '/test/bla/bla/bla', { |
| 38 | param: 'value' |
| 39 | }, { |
| 40 | authorization: 'my_token' |
| 41 | } ).then( ( data ) => { |
| 42 | assert.deepEqual( data, {}, 'If request succeeds without errors, resolve deferred' ); |
| 43 | } ); |
| 44 | } ); |
| 45 | |
| 46 | QUnit.test( 'http error', function ( assert ) { |
| 47 | const api = new CoreForeignRest( 'http://test.example.com/rest.php', this.actionApi ); |
| 48 | |
| 49 | this.server.respond( [ 404, {}, 'FAIL' ] ); |
| 50 | |
| 51 | api.get( '/test/rest/path' ) |
| 52 | .fail( ( errorCode ) => { |
| 53 | assert.strictEqual( errorCode, 'http', 'API error should reject the deferred' ); |
| 54 | } ) |
| 55 | .always( assert.async() ); |
| 56 | } ); |
| 57 | } ); |