Unexpected token encountered when testing Ajax call with JSON response

Currently, I have a Vue application with the following code snippet...

var vm = new Vue({
el: '#Workbooks',
components: {
    'workbook-list': workbooklist
},
data: {
    workbooks: [],
    message: '',
    loading: true,
    error: false
},
mounted: function () {
    this.getWorkbooks();
},
methods: {
    getWorkbooks: function () {
        var that = this;
        $.ajax({
            type: 'GET',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            url: '/LandingPage/getWorkbooks',
            success: function (response) {
                var results = JSON.parse(response);
                that.workbooks = results.workbooks.workbook;
                that.checkResults();
            },
            error: function (xhr, exception) {
                that.loading = false;
                that.message = 'Apologies, there was an issue fetching your reports. Please try again later.';
                that.error = true,
                console.log(xhr.status + ' ' + exception);
            },

        });
    },
     checkResults: function() {
        this.workbooks.length ? this.loading = false : this.message = 'You currently do not have any reports set up.';
    }
},

});

Everything is functioning properly, but I aim to test whether it's handling successful AJAX calls as expected.

Presently, I am executing the following Jasmine code through Karma...

it('should validate the results on successful Ajax call', function () {
    spyOn(vm, "checkResults");
    spyOn($, 'ajax').and.callFake(function (e) {
        e.success({}); 
    });

    vm.getWorkbooks();

    expect("checkResults").toHaveBeenCalled();
});

Two issues face me at the moment. Firstly, I'm encountering a 404 error in the logs regarding the AJAX URL (which directs to an ASP.NET MVC controller, rather than a physical file). Secondly, the test fails with 'SyntaxError: Unexpected token o in JSON at position 1'. It seems like this occurs because it's only returning an object and trying to parse non-existent JSON. Feel free to correct me if I'm mistaken.

My inquiry revolves around how to address these challenges and what's the proper method to unit test such AJAX calls since something appears amiss? In essence, I'm seeking ways to mock out that response.

Lastly, I'd like to mention that I'm utilizing these tools independently, without bundling them together or using Webpack.

I appreciate any assistance provided. Thank you.

Answer №1

Make sure to use ; instead of , in the code snippet below

that.loading = false;
that.message = 'Sorry, there was a problem fetching your reports. Please try later.';
that.error = true; // make sure to add ';' at the end of this line
console.log(xhr.status + ' ' + exception);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sorting Json Data Using Vue

My experience with Vue.js led me to a challenge I can't quite figure out: how to filter specific data in a Json file. Let me provide more context: I have a Json file filled with various electronics products such as computers, mice, keyboards, etc. I w ...

Using PHP to decode a JSON array (Troubleshooting issues with Ajax JSON POST to PHP)

I am new to PHP and I have a jQuery/JavaScript based application that involves finding nearby places and presenting the results in a sorted order. I am attempting to move the sorting function from the HTML page to server-side PHP. This process includes ...

Stop duplicate messages from appearing in AJAX chat feature (JavaScript, PHP, MySQL)

I developed a real-time chat system using AJAX, Javascript, PHP, and MySQL. Chat data is sent via JSON from a PHP page that retrieves information from a MySQL database. Each message is stored in an array and fetched through an AJAX call at regular interva ...

What is the method for configuring Vue to utilize a value other than the value property in form fields?

I am facing a unique challenge. Consider this: <select name="screw[type]" v-model="form.screw.type"> <option value="My value" ><?php _e('My value', 'fiam'); ?></option> //[...] Now, in another part of my ...

Creating a new form upon clicking

By clicking the "Add New Job" link, a new form with three fields will appear. This is the primary form: <h2>JOB EXPERIENCE 1</h2> <div class="job-content"> <input type="text" value="Company" name="company" /> <input type="te ...

Data sent through AJAX messaging is not being acknowledged

I recently made an AJAX request and set it up like this: $.ajax({ data : { id : 25 }, dataType : 'json', contentType : 'application/json; charset=utf-8', type : 'POST', // the rest of the ...

Issue: "Access-Control-Allow-Origin does not allow origin null" error message is returned when attempting to access a PHP file using jQuery's ajax method with dataType text/html selected

Why am I encountering this issue in Chrome when using dataType text and HTML? It seems to work fine if I output JavaScript and set the dataType to script. How can I return non-JavaScript data from a PHP file? Client-side code: $.ajax({ url: ...

Can I pass a variable to the data() option of a Vue composition API component?

After defining a variable in the setup function: setup(props, context) { let name = "Tommy"; } How can this variable be accessed and used within the component? data() { return { myName: name } }, The variable is accessib ...

I am facing an issue with jQuery wherein I am unable to dynamically assign a variable to an element's

I have a function that adds list elements to the #exercise-checkbox-list using AJAX. This function works fine on the backend side, but there is an issue where the second time a user adds an exercise, the new exercise's ID ends up being the same as the ...

Utilizing Vue JS for filtering numerical data

When I search for letters, my code below works well. However, when it comes to numbers like flat_number, it gives me an error saying flat.flat_number.toLowerCase is not a function filteredList() { return this.Flats.filter((flat) => { return ( ...

How Vue3 enables components to share props

Having recently made the switch from Vue2 to Vue3, I find myself a bit perplexed about the best approach for sharing props among multiple components. My goal is to create input components that can share common props such as "type", "name", and so on. Previ ...

Is this session/token authentication mechanism suitable for my web API?

Today, I successfully implemented a session and token authentication system for my web api using http get/post rpc style. Here is the plan I followed: Key: action (param1, param2) : returnvalue1, returnvalue2 login (username, password) : sessionkey, tok ...

Error: The specified JSON path for Ajax request could not be

Although my expertise lies in C++, I must confess that my knowledge about web development is quite limited. Therefore, please bear in mind that my question requires a simple answer. Recently, I stumbled upon a fascinating C++ library for creating a web se ...

Having trouble displaying Laravel 5.4 vue components? Explore potential solutions within the Laravel Passport framework

Currently, I am in the process of installing passport and using Taylor's tutorial video on laracast for assistance with integrating it into my vue components. However, after pasting these components I'm experiencing some issues as it's not ...

Generating HTML elements on the server-side vs. retrieving data as JSON and dynamically creating elements using JavaScript

Looking to implement an AJAX search feature that will retrieve and display topics from a forum, including just the topic link and subject. My question is: Which method would be more efficient and quicker? Retrieve the threads list as a JSON string, co ...

Error: JSON data couldn't be processed due to an unexpected end, resulting in a SyntaxError at JSON.parse()

I'm currently working on making an ajax call to an API, but I keep encountering an error whenever I try to make the call. I've been troubleshooting this for hours and I can't seem to figure out what the issue is. At one point, I even removed ...

Tips for preventing the use of nested functions while working with AJAX?

Consecutively making asynchronous calls can be messy. Is there a cleaner alternative? The issue with the current approach is its lack of clarity: ajaxOne(function() { // do something ajaxTwo(function() { // do something ajaxThree() }); }); ...

Display a webpage in thumbnail form when hovering the mouse over it

I'm in the process of creating a website that contains numerous sub-pages. I want to display all the links on a single page and when a user hovers over a link, I want to show a thumbnail of the corresponding webpage within a tooltip. I've experi ...

Utilizing Vuex in Vue with vue-enterprise-boilerplate: A Step-by-Step Guide

I am attempting to incorporate Vuex into my project using the chrisvfritz/vue-enterprise-boilerplate template. However, I am facing uncertainty regarding how to proceed. Within the <script> section of the "courses.vue" view component, the code appea ...

Adding rows with DWR using specific Element IDs

Calling All Expert DWR Users! I am currently utilizing reverse Ajax to dynamically populate a table on a web page. After executing the following method: public static void addRows(String tableBdId, String[][] data) { Util dwrUtil = new Util(getSessi ...