I'm having an issue running a test on a large complicated Vuetify component with many smaller components, the important parts:
<cat-form
:dogs="dogs"
:cats="cats"
>
</cat-form>
.....
props: [
'availablecats',
'avaliabledogs'
],
.....
computed: {
advertisers() {
var dogs = JSON.parse(this.avaliabledogs)
return dogs
},
cats() {
var cats = JSON.parse(this.availablecats)
return cats
},
And then the test using Vue-utils:
describe('CreateCat', function () {
let props = {
avaliablecats : [{
name: 'cat1',
age: 2
},
{
name: 'cat2',
age: 4
}],
avaliabledogs : [{
name: 'dog1',
age: 3
},
{
name: 'dog2',
age: 8
}],
}
beforeEach(() => {
wrapper = mount(CreateCat, {
propsData: props,
computed: {
dogs() {
return props.avaliabledogs
},
cats() {
return props.avaliablecats
},
}
});
});
test('true is true', () => {
expect(true).toEqual(true)
})
});
This is the error I receive:
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
143 |
144 | cats() {
> 145 | var cats= JSON.parse(this.avaliablecats)
| ^
146 | return cats
147 | },
Firstly, I thought if I mocked the props data, then the computed method could be calculated and wouldn't consider this.avaliabledogs and this.avaliblecats as undefined. But that didn't work.
I next tried to mock the computed methods then the function wouldn't be called at all. But I'm still receiving exactly the same error.
I've also tried the below methods as an alternate way to set computed methods and props after mounting the wrapper rather than including them when I first mount the component.
wrapper.setProps({
avaliablecats : [{
name: 'cat1',
age: 2
},
{
name: 'cat2',
age: 4
}],
avaliabledogs : [{
name: 'dog1',
age: 3
},
{
name: 'dog2',
age: 8
}],
})
wrapper.setComputed({
cats: [{
name: 'cat1',
age: 2
},
{
name: 'cat2',
age: 4
}],
dogs: [{
name: 'dog1',
age: 3
},
{
name: 'dog2',
age: 8
}],
})
I then tried stubbing the entire 'cat-form' component that used dogs and cats. Again, still getting the error.
wrapper = mount(CreateCat, {
stubs: {
CatForm: true,
},
I'm at a bit of a loss now - I feel like I've used the right syntax but I am getting confused why the methods in the computed property are still being called when i've mocked the computed function?
Any help would be very much appreciated!
JSON.parse(this.avaliabledogs)
implies that avaliabledogs
prop is valid JSON string. While it's an array of objects in this test, converting it to a string results in something like:
[object Object],[object Object]
This is what infamous SyntaxError: Unexpected token o in JSON
error indicates.
In this case there's no need to mock computed properties (can be done like shown here) because they are too small to be considered separate units that need to be isolated; this can be achieved with properly mocked props:
let props = {
avaliablecats : JSON.stringify([{
name: 'cat1',
age: 2
},
{
name: 'cat2',
age: 4
}]),
avaliabledogs : JSON.stringify([{
name: 'dog1',
age: 3
},
{
name: 'dog2',
age: 8
}]),
}