Created
April 9, 2023 19:52
-
-
Save daniel08s/2a47b64cc6fc0cf527be24b8cb6635be to your computer and use it in GitHub Desktop.
How To - Create an expectation on the fly with MockServer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mockServerClient = require('mockserver-client').mockServerClient; | |
const initialExpectation = { | |
'httpRequest': { | |
'method': 'POST', | |
'path': '/trigger', | |
'body': { | |
'value': 'example' | |
} | |
}, | |
'httpResponse': { | |
'statusCode': 200, | |
'body': JSON.stringify({ | |
'id': '12345' | |
}) | |
} | |
}; | |
const subsequentExpectation = { | |
'httpRequest': { | |
'method': 'GET', | |
'path': '/resource', | |
'queryStringParameters': { | |
'id': '12345' | |
} | |
}, | |
'httpResponse': { | |
'statusCode': 200, | |
'body': JSON.stringify({ | |
'value': 'example' | |
}) | |
} | |
}; | |
mockServerClient('localhost', 1080) | |
.mockAnyResponse(initialExpectation) | |
.then(() => { | |
console.log('Initial expectation registered.'); | |
}) | |
.catch((error) => { | |
console.log('Error registering initial expectation:', error); | |
}); | |
mockServerClient('localhost', 1080) | |
.mockResponseCallback((request) => { | |
if (request.method === 'POST' && request.path === '/trigger' && request.body.value === 'example') { | |
console.log('Initial request received.'); | |
const id = JSON.parse(request.body).id; | |
const newExpectation = { | |
'httpRequest': { | |
'method': 'GET', | |
'path': '/resource', | |
'queryStringParameters': { | |
'id': id | |
} | |
}, | |
'httpResponse': { | |
'statusCode': 200, | |
'body': JSON.stringify({ | |
'value': 'example' | |
}) | |
} | |
}; | |
return Promise.all([ | |
mockServerClient('localhost', 1080).mockAnyResponse(newExpectation), | |
mockServerClient('localhost', 1080).verify(newExpectation) | |
]) | |
.then(() => { | |
console.log('New expectation registered.'); | |
return { | |
'statusCode': 200, | |
'body': 'Initial response' | |
}; | |
}) | |
.catch((error) => { | |
console.log('Error registering new expectation:', error); | |
return { | |
'statusCode': 500, | |
'body': 'Internal server error' | |
}; | |
}); | |
} else { | |
return { | |
'statusCode': 404, | |
'body': 'Not found' | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment