Does Selenium maintain a cache? I'm confused why my JavaScript doesn't load during the tests

I have a more complicated question, but I am trying to narrow down the issue to avoid any confusion.

While testing a page using Selenium, I encountered an anomaly. The page contains two external JavaScript scripts. When visiting the page manually, everything works fine. However, when using Selenium, one of the JavaScript files fails to load:

The script from “http://localhost:55234/static/js/common.js” was loaded even though its MIME type (“text/html”) is not a valid JavaScript MIME type.
2 add-name
Loading failed for the <script> with source “http://localhost:55234/static/js/common.js”.

Upon checking the page source (right-click => view page source), I can see that the template includes the following lines among others:

[...] 
<!-- load global javascript -->
    <script type='text/javascript' src="/static/js/common.js"></script>
<!-- load app javascript -->
  <script type='text/javascript' src="/static/lists/js/lists.js"></script>
[...]

You can click on the `src` links in the source. Clicking the first link removes the last two lines related to `lists.js`, which means it fails to load:

<!-- load app javascript -->
  <script type='text/javascript' src="/static/lists/js/lists.js"></script>

Clicking the second link (`lists.js`) reveals an old version of the code. It seems like the browser cache might be causing this discrepancy since you recently disabled caching. However, these settings are different when the page is opened through Selenium. Would clearing the cache resolve the issue?

You also shared a code snippet to disable the cache entirely while setting up the WebDriver. Have you tried implementing this solution already?

Here's an excerpt from your codebase:

My template base.html:

[...]
<head>
  [...]
  <!-- load global javascript -->
  <script type='text/javascript' src="{% static '/js/common.js' %}"></script>
  <!-- load app javascript -->
  {% block script %}{% endblock %}
[...]

my template list.html

{% block script %}
  <script type='text/javascript' src="{% static 'lists/js/lists.js' %}"></script>
{% endblock %}

Based on the path references provided, everything seems correct in terms of file locations and inclusion within templates.

Within test.py:

class NameFormSeleniumTest(LiveServerTestCase):
    def setUp(self):
        self.browser = webdriver.Firefox()
        self.browser.implicitly_wait(2)

    def tearDown(self):
        self.browser.quit()

    def test_form_can_save_a_name(self):
    # some code
    # english = ...
    self.browser.get(self.live_server_url + '/lists/add-name/')
    Select(self.browser.find_element_by_id('id_namelanguage')).\
        select_by_value(str(english.id))
    # ...
    breakpoint()
    form = NameForm({'nametype': nome.id, 'gender': maschio.id,
                     'name': 'Remo', 'namelanguage': english.id,
                     'usato': 0})
    print(form.errors)
    form.save()

The error message thrown during testing indicates a validation failure because the necessary data wasn't present. Furthermore, inspection via `breakpoint()` shows that a specific JavaScript function is missing, leading to incomplete form submission and subsequent errors.

Your insights and assistance are greatly appreciated.

Answer №1

The issue has been identified and resolved.

Upon reviewing the documentation, it was noted that:

During tests utilizing real HTTP requests with LiveServerTestCase, it is essential to serve static assets along with other content for a more accurate replication of the production environment. However, LiveServerTestCase only offers basic static file-serving functionality without considering the finders feature of the staticfiles application, assuming that static content has already been collected under STATIC_ROOT.

To address this limitation, django.contrib.staticfiles.testing.StaticLiveServerTestCase is provided by staticfiles as a subclass of LiveServerTestCase, enabling seamless asset serving during test execution akin to what we experience in development mode with DEBUG = True, eliminating the need to run collectstatic beforehand.

It was determined that an outdated version of the javascript script was being loaded. As suggested in the documentation, switching to using StaticLiveServerTestCase instead of LiveServerTestCase resolves this issue.

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

Running queries in a loop is not functional within node-firebird

When running multiple select queries in a loop, I encountered an issue that puzzled me. For simplicity, let's take a look at the code snippet below: var Firebird = require('node-firebird'); Firebird.attach({database: 'TEST'}, (e ...

Differences Among Viewport, Window, and DocumentThese

Examining the code snippet provided below: document.documentElement.clientWidth 1349 document.documentElement.clientHeight 363 window.innerWidth 1366 window.innerHeight 363 window.screen.height 768 window.screen.width 1366 Therefore, my ...

Tips for creating a new Y-axis scale in a Google chart

I've been through numerous stackoverflow posts looking for a solution, but I still can't figure out how to add an additional Y scale in my Google chart. Can anyone assist me? Here is what my current output looks like: However, this is the desir ...

Strategies for restricting a runner within JUnitCore.runClasses()

I have numerous classes and multiple tests. However, when I utilize the following code: public class ParallelComputerExample { @Test public void runAllTests() { Class<?>[] classes = { Class1.class, Class2.class, Class3.class }; ...

Setting Metadata Dynamically in Vue Router

Currently, I have a Single Page Application (SPA) built with Vue and Vue Router. The setup mimics an iOS app where the title in the navigation bar changes as you navigate deeper into the views. Right now, the titles are hardcoded in the routes.js file, but ...

Guide on creating a cookie in express following a successful API call

Throughout my entire application, I utilize the /api route to conceal the actual API URL and proxy it in express using the following code: // Proxy api calls app.use('/api', function (req, res) { let url = config.API_HOST + req.url // This ret ...

Utilize Aframe to easily view and upload local gltf files

I've been working on a project to create a user-friendly panel for loading and viewing gltf models in real-time in A-frame. Here is the current workflow I am following: Using the input tag to load files from local storage. Using v-on-change to assi ...

Conceal the getter function or insert it into the prototype Object

Is there a way I can create a getter and hide it or add it to proto? For example, using a simple OBJ. Take a look at get sprite() buttonsData[name] = { name:name, type:bType, slot:slot, get sprite() { return this.slot.c ...

Struggling to dynamically access element IDs with JavaScript

As I loop through my list of students and add them to my page, I encounter an issue where each student's unique ID is not being passed correctly. When the getStudentInfo function is called, it always returns the ID of student1, regardless of which stu ...

Vue JS - preventing button from being enabled until all validation errors have been resolved

I am facing an issue with my button that is supposed to be disabled until all validation requirements are met. Currently, the button only gets disabled after I click it for the first time and encounter validation errors. I need the button to be disabled ri ...

Issue with Vuex getter not reflecting correct value after modifying an array

I've been delving into the world of vuex, and I'm currently working on fetching the count or an array when I make additions or removals. Below, you'll find the code snippets I'm working with. home.vue template <template> < ...

Troubleshoot: Node Express experiencing issues reconnecting to ajax

Here is the initial question that needs to be addressed. I am currently developing an API that links a front-end application (built using node, express, and Ajax) with a Python swagger API. The issue I am facing is that although I can successfully send da ...

Optimizing File Information Retrieval with C# Caching Techniques

After reviewing the MSDN documentation on the FileInfo.Name property, it appears that the data is initially cached upon first call and subsequent updates require the use of the Refresh method. I have a few questions that are either not covered or unclear ...

Transform jQuery code into vanilla JavaScript

I'm struggling with converting this part of code from jQuery to plain JavaScript. I've documented everything in a JSFiddle as an illustration. The following is the script: $(".button").click(function () { $pageID = $(this).attr('name& ...

How to select specific folders for packaging with asar within an Electron app

I'm currently working on an Electron application and experimenting with using asar to package the node_modules and sources directories, while excluding other directories. However, I've run into an issue where when building the application with a ...

Ajax request triggers a page refresh

As I review the AJAX call within a React method, there are some key observations: handleActivitySubmit: function handleActivitySubmit(activity, urlActivity, callbackMy) { console.log("querying with activity: " + JSON.stringify(activity)); $.ajax ...

How can we display the Recent Updates from our LinkedIn profile on our website using iframe or javascript?

Currently, I am in the process of developing a .NET web application for our company's website. We already maintain an active LinkedIn profile where we regularly post updates. https://i.stack.imgur.com/T2ziX.png My main query at this point is whether ...

Utilizing React to adapt to varying HTML layouts while maintaining consistent component usage

How can I create an App with two different views for mobile and desktop without relying solely on CSS Media Queries? I have been searching for guidance but so far haven't found a solution. Any advice or direction on where to find documentation or oth ...

There are a pair of unique on.change() functions in JQuery along with a single ajax request happening

I have a situation where I am working with two dropdowns in Python that are connected through Ajax calls. Below is the relevant code snippet from the HTML file: <script> $("#id_city").change(function () { // event on the city dropd ...

What is the best way to align row elements in Bootstrap?

Hey there everyone! I've been grappling with a challenge for the past few days on how to center the contents of a Bootstrap row. Let me elaborate: The row has 12 columns (as is standard in Bootstrap). However, in my design, I'm only utilizing 9 c ...