Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -308,13 +308,19 @@ let moxios = {

/**
* Stub a response to be used to respond to a request matching a method and a URL or RegExp
* The first parameter is optional for backwards compatability reasons. It might change to
* a required parameter in the future. Please always specify a method
*
* @param {String} method An axios command
* @param {String} [method] An axios command
* @param {String|RegExp} urlOrRegExp A URL or RegExp to test against
* @param {Object} response The response to use when a match is made
*/
stubRequest: function (urlOrRegExp, response) {
this.stubs.track({url: urlOrRegExp, response});
stubRequest: function(...args) {
if (args.length === 3) {
this.stubs.track({method: args[0], url: args[1], response: args[2]});
} else {
this.stubs.track({url: args[0], response: args[1]});
}
},

/**
Expand Down
67 changes: 67 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,73 @@ describe('moxios', function () {
})
})

it('should stub GET requests', function (done) {
moxios.stubRequest('GET', '/users/12345', {
status: 200,
response: USER_FRED
})

axios.get('/users/12345').then(onFulfilled)

moxios.wait(function () {
let response = onFulfilled.getCall(0).args[0]
deepEqual(response.data, USER_FRED)
done()
})
})

it('should stub POST requests, but not GET requests', function (done) {
moxios.stubRequest('POST', '/users/', {
status: 200,
response: USER_FRED
})

axios.get('/users/').then(onFulfilled)
axios.post('/users/', USER_FRED).then(onFulfilled)

moxios.wait(function () {
equal(onFulfilled.calledOnce, true)
let response = onFulfilled.getCall(0).args[0]
deepEqual(response.data, USER_FRED)
done()
})
})

it('should pick the correct stub based on method', function (done) {
const USER_WILMA = {
id: 54321,
firstName: 'Wilma',
lastName: 'Flintstone'
}

moxios.stubRequest('GET', '/users/', {
status: 200,
response: USER_FRED
})

moxios.stubRequest('POST', '/users/', {
status: 200,
response: USER_WILMA
})

moxios.stubRequest('PUT', '/users/', {
status: 200,
response: USER_FRED
})

axios.put('/users/', USER_FRED).then(onFulfilled)
axios.post('/users/', USER_WILMA).then(onFulfilled)

moxios.wait(function () {
equal(onFulfilled.calledTwice, true)
let response = onFulfilled.getCall(0).args[0]
deepEqual(response.data, USER_FRED)
response = onFulfilled.getCall(1).args[0]
deepEqual(response.data, USER_WILMA)
done()
})
})

it('should stub timeout', function (done) {
moxios.stubTimeout('/users/12345')

Expand Down