Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mock axios in module style #42

Closed
craigcosmo opened this issue Mar 17, 2017 · 3 comments
Closed

mock axios in module style #42

craigcosmo opened this issue Mar 17, 2017 · 3 comments

Comments

@craigcosmo
Copy link

craigcosmo commented Mar 17, 2017

I got code like this

method.js

export function deleteImageFromServer(id){
	return axios.post('http://localhost:8000/'+'delete', {id:id})
}

home.spec.js

import {deleteImageFromServer} from './method'
import MockAdapter from 'axios-mock-adapter'
import axios from 'axios'
import {expect} from 'chai'

describe('deleteImageFromServer', function () {
	it('should delete image', function () {

		let mock = new MockAdapter(axios)
		mock.onPost('http://localhost:8000/delete').reply(function(){
			return [200, 'success']
		})
		deleteImageFromServer(1).then( (r) =>{
			expect(r.data).to.equal('success')
		})
	})
})

I don't know why the intercept never happens.

@ctimmerm
Copy link
Owner

You're doing some asynchronous stuff, but you're not waiting for it to finish. If you're using Mocha, you can return a promise:

import {deleteImageFromServer} from './method'
import MockAdapter from 'axios-mock-adapter'
import axios from 'axios'

describe('deleteImageFromServer', function () {
	it('should delete image', function () {

		let mock = new MockAdapter(axios)
		mock.onPost('http://localhost:8000/delete').reply(function(){
			return [200, 'success']
		})
		return deleteImageFromServer(1).then( (r) =>{
			expect(r.data).to.equal('success')
		})
	})
})

@craigcosmo
Copy link
Author

@ctimmerm thanks, that works, but I don't know why would the 'return' keyword means waiting in this case, can you explain more?

@ctimmerm
Copy link
Owner

It's Mocha feature: https://mochajs.org/#working-with-promises. When you return a promise, Mocha can wait for the promise to resolve.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants