Prevent linebreaks in Prettier - prettier

How can I prevent prettier from adding line breaks to the beginning of my .then() and .catch() statements
Expected
await Axios({
method: "GET",
url: test,
}).then((response) => {
...
}).catch((exception) => {
...
});
Actual
await Axios({
method: "GET",
url: test,
})
.then((response) => {
...
})
.catch((exception) => {
...
});

Related

Axios not returning "set-cookie"

I can't understand why Axios doesn't return set-cookies
Code:
axios({
url: 'https://*/bpms/engine/get_profile.php',
withCredentials: false, // true return same
auth: {
username: this.emailValue,
password: this.passwordValue
},
headers: {"Cache-Control": "max-age=0"}
})
.catch((error) => {
if (error) {
alert(error.response.data.error.description);
document.location.reload()
}
})
.then(response => {console.log(response.headers)})}
Browser network request:
Axios response.headers:

axios Post request returns null response

I am facing an issue of receiving NULL response for the axios POST request I made. How do I correct this error?
I've tried to changing multipart/form-data into x-www-form-urlencoded and multipart/x-www-form-urlencoded
async submitUser() {
this.memberObj = {
id: this.memberObjLocal.id,
name: this.memberObjLocal.name,
password: this.memberObjLocal.password,
email: this.memberObjLocal.email,
password: this.memberObjLocal.password,
gender: this.memberObjLocal.gender,
experience: this.memberObjLocal.experience,
birth: this.memberObjLocal.birth,
phoneNum: this.memberObjLocal.phoneNum,
address: this.address,
introduce: this.introduce,
pic: this.pic
};
const config = {
headers: { "Content-Type": "multipart/form-data" }
};
var formData = new FormData();
for (let data in this.memberObj) {
console.log(data);
formData.append(data, this.memberObj[data]);
console.log(this.memberObj[data]);
}
for (var key of formData.entries()) {
console.log(key[0] + ", " + key[1]);
}
try {
let response = await this.$axios.$post("/users/", formData, config);
this.$router.push("/");
console.log(response) // null
} catch (e) {
console.log(e.response);
}
}
Please try to use like this
import axios from "axios";
//... your codes here
axios({
url: "/users/",
method: "post",
data: formData,
headers: config.headers
})
.then(response => {
this.$router.push("/");
console.log(response);
})
.catch(error => console.error(error));
//... and other codes here
and you can see more examples!

How to test async function with axios?

I need to test async function using mocha.
Tried to test function that returns Promise from axios. Looked through many examples with axios-mock-adapter to solve my issue. BUT: axios sends REAL request, not mock as expected.
describe ('login sendRequest', () => {
let sandbox = null;
before(() => {
sandbox = sinon.createSandbox();
});
after(() => {
sandbox.restore();
});
it('should create and return REST promise', done => {
const mockAdapter = new MockAdapter(axios);
const data = { response: true };
mockAdapter.onAny('http://google.com').reply(200, data);
const requestParams = {
method: 'post',
url: 'http://google.com',
data: {},
adapter: adapter,
};
logic.sendRequest(requestParams).then(response => {
console.log(response);
done();
}).catch(err => {
console.log(err);
});
});
});
logic.js
export async function sendRequest(requsetParams) {
return await requestSender.request(requsetParams);
}
Expected to get 200 response and mock data that was set before. Why I don't get the response I need? May someone help?

Vue.js (2.0) unit test issue

I am trying to perform unit test on vuex actions, using Mocha and Sinon
here is my action.spec.js
import actions from '#/vuex/actions'
import * as types from '#/vuex/mutation_types'
describe('actions.js', () => {
var server, store, lists, successPut, successPost, successDelete
successDelete = {'delete': true}
successPost = {'post': true}
successPut = {'put': true}
beforeEach(() => {
// mock shopping lists
lists = [{
id: '1',
title: 'Groceries'
}, {
id: '2',
title: 'Clothes'
}]
// mock store commit and dispatch methods
store = {
commit: (method, data) => {},
dispatch: () => {
return Promise.resolve()
},
state: {
shoppinglists: lists
}
}
sinon.stub(store, 'commit')
// mock server
server = sinon.fakeServer.create()
server.respondWith('GET', /shoppinglists/, xhr => {
xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify(lists))
})
server.respondWith('POST', /shoppinglists/, xhr => {
xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify(successPost))
})
server.respondWith('PUT', /shoppinglists/, xhr => {
xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify(successPut))
})
server.respondWith('DELETE', /shoppinglists/, xhr => {
xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify(successDelete))
})
server.autoRespond = true
})
afterEach(() => {
// restore stubs and server mock
store.commit.restore()
server.restore()
})
describe('populateShoppingLists', () => {
it('should call commit method with POPULATE_SHOPPING_LIST string parameter', done => {
actions.populateShoppingLists(store).then(() => {
expect(store.commit).to.have.been.calledWith(types.POPULATE_SHOPPING_LISTS, lists)
done()
}).catch(done)
})
})
describe('changeTitle', () => {
it('should call commit method with CHANGE_TITLE string', (done) => {
let title = 'new title'
actions.changeTitle(store, {title: title, id: '1'}).then(() => {
expect(store.commit).to.have.been.calledWith(types.CHANGE_TITLE, {title: title, id: '1'})
done()
}).catch(done)
})
})
describe('updateList', () => {
it('should return successful PUT response', (done) => {
actions.updateList(store, '1').then((data) => {
expect(data.data).to.eql(successPut)
done()
}).catch(done)
})
})
describe('createShoppingList', () => {
it('should return successful POST response', (done) => {
let newList = { title: 'new list', id: '3' }
actions.createShoppingList(store, newList).then((testResponse) => {
console.log('testResponse: ', testResponse)
expect(testResponse.body).to.eql(successPost)
done()
}).catch(done)
})
})
})
here is my action.js
import { CHANGE_TITLE, POPULATE_SHOPPING_LISTS } from './mutation_types'
import api from '../api'
import getters from './getters'
export default {
populateShoppingLists: ({ commit }) => {
return api.fetchShoppingLists().then(response => {
commit(POPULATE_SHOPPING_LISTS, response.data)
})
},
changeTitle: (store, data) => {
store.commit(CHANGE_TITLE, data)
return store.dispatch('updateList', data.id)
},
updateList: (store, id) => {
let shoppingList = getters.getListById(store.state, id)
return api.updateShoppingList(shoppingList)
},
createShoppingList: (store, shoppinglist) => {
return api.addNewShoppingList(shoppinglist).then((actionResponse) => {
console.log('actionResponse: ', actionResponse)
store.dispatch('populateShoppingLists')
})
},
}
running my unit tests , I have an issue with the createShoppingList test
console.log
actions.js
populateShoppingLists
✓ should call commit method with POPULATE_SHOPPING_LIST string parameter
changeTitle
✓ should call commit method with CHANGE_TITLE string
updateList
✓ should return successful PUT response
LOG LOG: 'actionResponse: ', Response{url: 'http://localhost:3000/shoppinglists', ok: true, status: 200, statusText: 'OK', headers: Headers{map: Object{Content-Type: ...}}, body: Object{post: true}, bodyText: '{"post":true}'}
LOG LOG: 'testResponse: ', undefined
createShoppingList
✗ should return successful POST response
undefined is not an object (evaluating 'testResponse.body')
webpack:///test/unit/specs/vuex/actions.spec.js:90:28 <- index.js:15508:28
webpack:///~/vue-resource/dist/vue-resource.es2015.js:151:0 <- index.js:17984:52
webpack:///~/vue/dist/vue.esm.js:701:0 <- index.js:3198:18
nextTickHandler#webpack:///~/vue/dist/vue.esm.js:648:0 <- index.js:3145:16
whicj indicates that in the createShoppingList action, the reponse is not sent back on the return, so expect(testResponse.body).to.eql(successPost) is not true...
what's wrong with my Promise handling in this case ?
thanks for feedback
You're on the right track - testResponse is undefined, because createShoppingList resolves with the return value of addNewShoppingList.then, which is unspecified, and defaults to undefined.
Should createShoppingList resolve with addNewShoppingList's response or the response from populateShoppingLists? If the former, return actionResponse from the handler:
return api.addNewShoppingList(shoppinglist).then((actionResponse) => {
store.dispatch('populateShoppingLists')
return actionResponse
});
As a side-note, because the actions you're testing are promises, you can get rid of done in your tests by returning the actions directly:
it('should call commit method with POPULATE_SHOPPING_LIST string parameter', () => {
// mocha will fail the test if the promise chain rejects or the expectation is not met
return actions.populateShoppingLists(store).then(() => {
expect(store.commit).to.have.been.calledWith(types.POPULATE_SHOPPING_LISTS, lists)
})
})

How to upload video to facebook via FB api with javascript?

How can I upload video files to facebook using FB api? I looked around stackoverflow but I can only find answers when the video/picture is already online somewhere, but I want to let the user directly upload a file to facebook via my application.
One solution that can upload to facebook is https://stackoverflow.com/a/8195849/364938, but it assumes I have the picture online somewhere.
Is this even possible? If if is, then how?
This is my code for uploading video using javascript from client side.I used axios for http requests, but you can use your own.
function uploadVideo(adaccount, access_token, file) {
return axios({
method: 'POST',
url: `${adaccount}/advideos`,
params: {
access_token,
upload_phase: 'start',
file_size: file.size
}
})
.then(res => {
return new Promise(resolve => {
resolve(transferVideo(
adaccount,
access_token,
res.data.upload_session_id,
res.data.start_offset,
res.data.end_offset,
file,
1
))
})
})
.catch(err => {
// Note: you can handle your error here
console.log(err)
})
}
function transferVideo(adaccount, token, sessionId, start, end, file, number) {
if (start === end) {
return new Promise(resolve => {
resolve(postVideo(adaccount, token, sessionId, file.name))
})
}
const blob = new Blob([file], {
type: file.type
})
const chunk = blob.slice(start, end, file.type)
const formData = new FormData()
formData.append(
'video_file_chunk',
chunk,
`#chunk${number}.${file.type.split('/')[1]}`
)
return new Promise(resolve => {
resolve(uploadVideoChunk(
adaccount,
token,
start,
sessionId,
formData
))
})
.then(res => {
return new Promise(resolve => {
resolve(transferVideo(
adaccount,
token,
sessionId,
res.start_offset,
res.end_offset,
file,
number++
))
})
})
.catch(err => {
throw new Error(JSON.stringify(err))
})
}
function uploadVideoChunk(adaccount, access_token, start_offset, upload_session_id, formData) {
return axios.post(`${adaccount}/advideos`, formData, {
headers: {
'content-type': 'multipart/form-data'
},
params: {
access_token,
upload_phase: 'transfer',
start_offset,
upload_session_id
}
})
.then(res => res.data)
.catch(err => {
throw new Error(JSON.stringify(err))
})
}
function postVideo(adaccount, access_token, upload_session_id, title) {
return axios({
method: 'POST',
url: `${adaccount}/advideos`,
params: {
access_token,
upload_phase: 'finish',
upload_session_id,
title
}
})
.then(res => res.data)
.catch(err => {
throw new Error(JSON.stringify(err))
})
}