|
| 1 | +const assert = require('assert') |
| 2 | +const REST = require('../../../lib/helper/REST') |
| 3 | +const Container = require('../../../lib/container') |
| 4 | + |
| 5 | +const TestHelper = require('../../support/TestHelper') |
| 6 | +const axios = require('axios') |
| 7 | +const fallBackURL = 'https://jsonplaceholder.typicode.com' |
| 8 | +//start the server using npm run test-server as in the package.json |
| 9 | +let api_url = TestHelper.jsonServerUrl() |
| 10 | + |
| 11 | +describe('REST onResponse Hook Wrapper', () => { |
| 12 | + let rest |
| 13 | + |
| 14 | + beforeEach(async () => { |
| 15 | + Container.helpers({}) |
| 16 | + try { |
| 17 | + await axios.get(`${api_url}`, { timeout: 1000 }) // Check if the server is reachable |
| 18 | + } catch (e) { |
| 19 | + api_url = fallBackURL // Fallback to alternative endpoint |
| 20 | + } |
| 21 | + |
| 22 | + rest = new REST({ |
| 23 | + endpoint: api_url, |
| 24 | + onResponse: res => { |
| 25 | + res.customFlag = true |
| 26 | + }, |
| 27 | + }) |
| 28 | + |
| 29 | + rest._before() |
| 30 | + }) |
| 31 | + |
| 32 | + afterEach(() => { |
| 33 | + rest = null |
| 34 | + }) |
| 35 | + |
| 36 | + it('should store response in this.response', async () => { |
| 37 | + const response = await rest.sendGetRequest('/posts/1') |
| 38 | + assert.ok(response, 'Expected response to be set on REST instance') |
| 39 | + assert.equal(response.status, 200) |
| 40 | + }) |
| 41 | + |
| 42 | + it('should call onResponse function and preserve modifications', async () => { |
| 43 | + const response = await rest.sendGetRequest('/posts/1') |
| 44 | + assert.ok(response.customFlag, 'Expected original onResponse to run and modify response') |
| 45 | + }) |
| 46 | + |
| 47 | + it('should not fail if original onResponse is not set in the config', async () => { |
| 48 | + const restNoHook = new REST({ endpoint: api_url }) |
| 49 | + restNoHook._before() |
| 50 | + |
| 51 | + const response = await restNoHook.sendGetRequest('/posts/1') |
| 52 | + assert.ok(response, 'Expected response to be returned') |
| 53 | + assert.equal(response.status, 200) |
| 54 | + }) |
| 55 | + |
| 56 | + it('should not throw if onResponse is not a function in the config', async () => { |
| 57 | + const restInvalid = new REST({ |
| 58 | + endpoint: api_url, |
| 59 | + onResponse: undefined, |
| 60 | + }) |
| 61 | + |
| 62 | + restInvalid._before() |
| 63 | + |
| 64 | + const response = await restInvalid.sendGetRequest('/posts/1') |
| 65 | + assert.ok(response) |
| 66 | + assert.equal(response.status, 200) |
| 67 | + }) |
| 68 | +}) |
0 commit comments