Skip to content

Instantly share code, notes, and snippets.

  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save daniel08s/2a47b64cc6fc0cf527be24b8cb6635be to your computer and use it in GitHub Desktop.
How To - Create an expectation on the fly with MockServer
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