I need to mock an fetch call which returns an array with Jest Fetch Mock:
https://jsonplaceholder.typicode.com/todos/
it ('<Main />', () => {
const wrapper = render (<Main />);
fetch.mockResponseOnce (
JSON.stringify ([
{
id: '1',
title: 'hi',
},
])
);
wrapper.debug ();
});
However I'm getting an error:
(node:4667) UnhandledPromiseRejectionWarning: FetchError: invalid json response body at undefined reason: Unexpected end of JSON input
Related
i am doing testing, i made a test in that test i create a mock for a fake function
jest.mock('#/services/myService', ()=>({getAvailables: jest.fn().mockReturnValue()}))
that function is running in my component
onMounted(async () => {
const answer = await getAvailables1()
const answer = await getAvailables2()
const answer = await getAvailables3()
but still i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables1) is not a function
(node:81921) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag
if i put like this first getAvailables2
onMounted(async () => {
const answer = await getAvailables2()
const answer = await getAvailables1()
i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables2) is not a function
if i put like this first getAvailables3
onMounted(async () => {
const answer = await getAvailables3()
const answer = await getAvailables2()
i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables3) is not a function
also i try with mockResolvedValue, does not worked
export const getAvailables = async () => {
let response
let error
try {
response = await getData()
} catch (err) {
error = err
throw err
}
return { response, error }
}
It looks like you want a mock partial:
jest.mock('#/services/myService', () => {
const originalModule = jest.requireActual('#/services/myService');
return {
__esModule: true,
...originalModule,
getAvailables1: () => Promise.resolve({ foo: 'bar' }),
getAvailables2: () => Promise.resolve({ foo: 'baz' }),
getAvailables3: () => Promise.resolve({ foo: 'bad' }),
/* any other method of your service that gets called */
};
});
This will mock the provided functions in the mock while the rest of the service will function as in the original.
getAvailables() is async function that always returns a promise.
So, in order to mock that function you need to return the mock promise with success or rejected value.
Following is the example of mocking that function which returns success promise.
jest.mock('#/services/myService', () => ({
getAvailables: jest.fn().mockResolvedValue(true)
}))
In my html I reference the directive: v-init:url="myurlhere"
data() {
return {
currentPage: 1,
url: '',
news: '',
}
},
directives: {
init: {
mounted(el, binding) {
console.log(binding.value);
this.iterateUrlContents(binding.value)
},
}
},
methods: {
iterateUrlContents(url) {
console.log('url: ' + url);
console.log(binding.value) shows the expected result, however when I call iterateUrlContents I get the following:
Unhandled error during execution of directive hook
Uncaught TypeError: Cannot read property 'iterateUrlContents' of
undefined
And I also find that if I try this.url = binding.value I get
Uncaught TypeError: Cannot set property 'url' of undefined
Why is binding.value undefined, and how can I pass this information to my method?
If you want to access the component instance you need to do it via binding.instance in Vue3.
In #vue/cli 4.0.5 / vuex 3 app with data reading from Laravel Backend API
I keep some parameters in database settings table and I want to read them once
and to keep it in vuex storage.
I check if site_name value is empty I
call retrieveSiteName action and got error :
Error in render: "TypeError: Cannot read property 'dispatch' of undefined"
In my src/store/index.js :
export default new Vuex.Store({
state: {// store data
status: '',
token: localStorage.getItem('token') || '',
user: null,
site_name: '', // I need to read this value once
...
}, // state: { // store data
getters: {
...
site_name(state) {
if (state.site_name.length > 0) {
return state.site_name
}
let site_name = localStorage.getItem('site_name')
if (site_name != null ) {
return site_name
}
// this.actions.retrieveSiteName(state)
// state.this.dispatch('retrieveSiteName')
this.dispatch('retrieveSiteName') // Error Here!
return ''
}, // site_name(state) {
...
actions: { // async methods
retrieveSiteName(context) {
console.log('retrieveSiteName::')
let apiUrl = process.env.VUE_APP_API_URL
axios.post(apiUrl + '/app_settings', 'site_name')
.then((response) => {
console.log('retrieveSiteName response::')
console.log(response)
context.commit('refreshSiteName', response.data.site_name)
})
.catch((error) => {
console.error(error)
})
}, // retrieveSiteName(context) {
Which is valid way of calling retrieveSiteName from get name method ?
Thanks!
My API url is http://localhost:5000/api/user/list, data shows as:
[{"Id":1,"name":"Michael","pwd":"123456","age":0,"birth":"2018-01-05","addr":"''"},{"Id":2,"name":"Jack","pwd":"123512616","age":0,"birth":"2018-01-05","addr":"''"}]
User.vue
import axios from 'axios';
export default {
data() {
return {
filters: {
name: ''
},
loading: false,
users: [
]
}
},
methods: {
getUser: function () {
axios.get('http://localhost:5000/api/user/list', function (data) {
this.$set('users', data);
})
}
},
mounted() {
this.getUser();
}
});
The error is :
Unhandled promise rejection Error: Request failed with status code 404(…)
How can I fix it?
You should register a handler for your axios request.
Currently you are using settings argument as a handler.
axios.get('http://localhost:5000/api/user/list').then(function (response) {
// this is your handler.
})
Btw, make sure you are not requesting via CORS.
In my case there was a spelling mistake in URL string. It is fixed after that correction.
I have a products component and a product owner component. Each Product will have an owner
What I am trying to do
I am receiving a list of products by calling an API endpoint. When the promise is resolved, I have a list of Products. Each Product has an OwnerID. I am trying to call another API Endpoint to fetch the name of the owner and assign it to the current product being iterated.
My Code so far
<script>
var config = require('../config');
export default {
data () {
return {
products: [],
}
},
ready () {
this.getProducts().then(t => {
console.log(t);
});
},
methods : {
getProducts : function() {
let url = config.API.GetProduct
this.$http.get(url).then(response=> {
this.products = response.data.resource;
var p = this.products.map(this.getOwner);
return Promise.all(p);
}, error=> {
console.error("An error happened!")
});
},
getOwner : function(product) {
let url = config.API.GetProductOwnerName.replace('[$$$]', product.OwnerID);
var p = new Promise();
this.$http.get(url).then(response => {
product.OwnerID = response.data.resource[0].OwnerName;
p.resolve(currentObj);
});
return p;
}
}
components: {}
}
</script>
Error that I am facing
Now whenever I am trying to do that, I keep getting the following errors
Uncaught TypeError: Cannot read property 'then' of undefined
Uncaught (in promise) TypeError: Promise resolver undefined is not a function(…)
Can somebody please let me know what I am doing wrong here ?
Thanks
You don't have to recreate a new promise object. You can just return the object you want to be passed to the next call.
getProducts: function() {
let url = config.API.GetProduct
return this.$http.get(url).then(response => {
this.products = response.data.resource;
return this.products.map(this.getOwner);
}, error=> {
console.error("An error happened!")
});
},