jQuery not found with Django RGBField - javascript

The project I'm working on uses an RGBField, which inserts this script into the template (which is deep in the bowels of django somewhere because I can't find where it lives):
<script type="text/javascript">
(function($){
$(document).ready(function(){
$('#id_color').each(function(i, elm){
// Make sure html5 color element is not replaced
if (elm.type != 'color') $(elm).colorPicker({"colors": ["f1c40f", "2ecc71", "9b59b6", "e74c3c", "34495e", "3498db", "1abc9c", "f39c12", "d35400"]});
});
});
})('django' in window && django.jQuery ? django.jQuery: jQuery);
</script>
In the console I'm getting an error: Uncaught ReferenceError: jQuery is not defined I'm unable to inspect where the error is happening, but removing the RGBField prevents the issue.
Jquery is used in the project, and if I use jQuery in the template itself it works fine (so it's not a problem with the template per se).
I've added django-jquery to the project, and included {% load staticfiles %} at the start of the template. Does not resolve the problem.
I've been ignoring the whole thing happily but now I need to write a cypress test with this page and the error is blocking the test.
Is there a way in cypress to ignore this error? Or is there a way to prevent the error from happening in the first place? Is there a flag for RGBField to turn off the check for jquery?
Running 'django' in window produces false, and running django.jQuery produces the error. Running 'django' in window && django.jQuery produces false so in theory this the second option should be taken, which when I run in the console is fine (but clearly I am missing something).
EDIT:
List of installed apps:
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.humanize',
'whitenoise.runserver_nostatic',
'storages',
'django.contrib.staticfiles',
'django.contrib.flatpages',
'jquery',
'django.contrib.sites',
'django_activeurl',
'webpack_loader',
'widget_tweaks',
'argonauts',
'rest_framework',
'main',

The error most likely relates to this line of code:
'django' in window && django.jQuery ? django.jQuery: jQuery
It maybe helpful to understand and consider the ternary conditional.
Out of the box, the Django Admin sets up a 'django' variable on the window global and pins jQuery to it. This is because the admin makes use of jQuery. Outside of the admin, in custom templates, it's up to the developer to decide how to include jQuery if they want it.
So the statement 'django' in window && django.jQuery willl evaluate to true on Django Admin pages and in the "true" side of the ternary, the snippet goes ahead and references it. Alternatively on the false side of the ternary, it's assumed jQuery is already present on the global scope. The reference to jQuery is then passed as a parameter into the IIFE.
I would look closely at your page source to determine if/where the jQuery module is referenced and ensure it's being loaded properly prior to that snippet.

By default, Cypress fails tests when there is an uncaught exception thrown. This behavior can be useful for many users and oftentimes alerts developers to bugs they were not aware of.
That being said, there are times when an uncaught exception is thrown and you would like to ignore it and carry on with your test (especially if it is being thrown from a 3rd party plugin). You can do this by using Cypress events.
To turn off all uncaught exception handling:
Cypress.on('uncaught:exception', (err, runnable) => {
// returning false here prevents Cypress from failing the test
return false
})
Likely you will want to do this in a support file (cypress/support/index.js) so it is applied to all spec files.

Related

Cypress hljs is not defined

I wrote a simple test to visit the site https://auth0.github.io/device-flow-playground/
describe('My First Test Suite', () => {
it("should navigate to the application", () => {
cy.visit("https://auth0.github.io/device-flow-playground/");
});
})
But, I am getting this error :
The following error originated from your application code, not from Cypress.
> hljs is not defined
When Cypress detects uncaught errors originating from your application it will automatically fail the current test.
This behavior is configurable, and you can choose to turn this off by listening to the uncaught:exception event
I understand that Cypress cannot do much here, but still looking for some pointers if there's some way to fix this so the page loads correctly? I don't have much of JS experience here.
The line that is likely (not definitely) to be causing your problem is
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/highlight.min.js"></script>
This adds library hljs to the page.
You can see the above script tag if you open https://auth0.github.io/device-flow-playground/ in a browser (not Cypress) and look at the Elements tab in devtools.
It's difficult to know why this script is blocked, because it works ok on my machine.
Try putting this URL https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/highlight.min.js in the browser also, may give you some clues.
Is there a firewall preventing you access to the above?

Web Component: Dom Exception: This name has already been used

tl:dr; I don't know how to fix the error below on the site here:
You will need credentials:
un: stackoverflowuserj23jf4#mailinator.com
pass: testingStackOverflow123
Details: I am trying to conditionally include a web component in a page like so:
<script>
document.addEventListener("DOMContentLoaded", function(event) {
if (document.querySelector('simple-fred')) {
var script = document.createElement('script');
script.src = 'https://embedint.crossroads.net/fred/js/simplefred.min.js';
document.head.appendChild(script)
}
});
</script>
Including the script conditionally instead of statically broke the code. The script above used to be loaded like this:
<script src="https://embedint.crossroads.net/fred/js/simplefred.min.js"></script>, which worked
I then include the element on the page:
<simple-fred data-form-name="buildingblocksformarriage" data-redirect-url="/care/weddings/building-blocks-for-marriage/signup/confirmation"> </simple-fred>
This works fine locally and on plunker.
To run it on plnkr, you do need to disable CORS blocking for Chrome, the command is:
TASKKILL /F /IM chrome.exe
start chrome.exe --args --disable-web-security --user-data-dir
pause
This is all good and well, but when I run this code in concert with other code, it fails. I get the following error (same error, browsers report it differently):
Chrome:
Uncaught DOMException: Failed to execute 'define' on
'CustomElementRegistry': this name has already been used with this
registry
at Function.value (https://embedint.crossroads.net/fred/js/simplefred.min.js:5:383105)
Mozilla:
Error: A custom element with name 'slim-repeat' has already been
defined.
This error seems to be caused by two third-parties trying to create the same custom component as far as I can tell judging by this question I have a bounty on
I am at a loss at this point. The int environment that throws the error is here:
https://int.crossroads.net/care/weddings/building-blocks-for-marriage/signup
You may need a login, I made one so it's faster (can be shared):
stackoverflowuserj23jf4#mailinator.com
testingStackOverflow123
The code is open source and is found here (I don't think looking at it will help, just for completeness): https://github.com/crdschurch/crds-fred/blob/development/CrdsFred/Views/Form/Index.cshtml
How do I fix this?
Or at least, what are possible causes? I will throw at least a 100 point bounty on this to reward the accepted answer.
it looks like there's a node module named slim-js, and it creates an element called slim-repeat on lines 1057 and/or 1146 of Slim.js (see screenshot). Maybe you just need to pick a different name?
I am the author of this library and would like to assist. I will deploy a hot fix for this Issue. Eventually not running the whole script if another instance of Slim is already initialized.

How do I test that Sentry is reporting errors?

I just installed Sentry for a client-side JavaScript app using the standard code snippet they provided. How do I test that it's working properly? I've tried manually throwing an error from my browser console and it didn't appear in Sentry. Is there any documentation on the right way to do this?
Verify (newer)
myUndefinedFunction();
Verifying Your Setup (older)
Sentry.captureException(new Error("This is my fake error message"));
https://docs.sentry.io/platforms/javascript/?platform=browser#verifying-your-setup
May be worth double-checking your setup (or updating) and config too.
The browser console can not be used as it is sandboxed. A simple trick is to attach the code to an HTML element like this:
<h1 onClick="throw new Error('Test')">
My Website
</h1>
And click on the heading afterwards.
This can be done in the browser inspector and so your source code doesn't have to be modified.
One way to generate an error in Sentry is to call a function that is not defined.
Note: This cannot be done in the console - it must be in the code.
Try adding this to your code (taken from the docs):
myUndefinedFunction();
If your code build doesn't allow this due to tests/linting you might be able to use:
window.myUndefinedFunction()
You should then see error in your browser console and in the Sentry dashboard.
Have a read of the Docs for more info.
Raven.captureMessage('Broken!') is a good place to start (also pulled from Sentry docs). If that fails to send, the Raven client isn't being initiated.
If you can't or don't want to use an undefined function to test Sentry is sending errors, you can also use the Debugger in Chrome's DevTools by:
Adding a breakpoint in your code e.g. for a click event handler
Trigger that event e.g. click a button
When the breakpoint hits in the console, set a function/variable that is needed for execution to undefined
Press play/continue in DevTools to then see the Error output
e.g.
1: function onClick() {
2: api.sendSomeEvent();
3: }
Add a breakpoint in the body of the onClick event handler (Line 2), trigger the event. When execution is paused: in your console enter something like api = undefined and hit enter to update the state. Then continue execution (click the play button), where you should see an error (ala api is undefined) that Sentry should then send for you.
Note: this works for any environment, though you may need to be clever with finding your events in minified code ;)

Finding a strange Javascript function 'window.ueLogError' in a PhantomJS error message

I'm working on a project that involves retrieving multiple websites with PhantomJS and when I try to load Amazon.com, PhantomJS crashes while trying to evaluate this function with the error:
TypeError: 'undefined' is not a function (evaluating 'window.ueLogError')
The weird thing is that I can't seem to find any documentation or explanation of any kind for window.ueLogError. A google search gives a handful of websites with scripts that contain it, but it doesn't seem to be a part of any documentation I can find. Does anyone know anything about ueLogError?
The window object is the global sink in the browser. Every variable that you define globally (e.g. jQuery's $) is a property in window. ueLogError is not some kind of standardized JavaScript function. It is most likely some function for an advertisement script.
Not all resources that a page requests as part of the page load are actually successfully loaded. Some requests fail due to SSL problems. Some requests fail, because the user agent string is not supported. Some requests fail because of unknown reasons.
You can register to the onConsoleMessage, onError, onResourceError, onResourceTimeout events (Example) to see whether there are errors. Usually you will find that some JavaScript file wasn't loaded which would have contained ueLogError which another script depends on.

Lazy loading knockoutjs with bookmarklet failing

I'm attempting to fix a bookmarklet I wrote to track the URL changes in a single page application, specifically recording timesheet while using asana. It uses a script loader to embed jQuery and KnockoutJS libraries before init. I'm unable to find the ko object in global scope after the KnockoutJS library has initialized and cannot figure out why. To test, login to https://app.asana.com, open the Google Chrome developer tools' Console tab and try the following code:
var koScript=document.createElement('script');
koScript.type='text/javascript';
koScript.src='//ajax.aspnetcdn.com/ajax/knockout/knockout-3.0.0.js';
document.getElementsByTagName('head')[0].appendChild(koScript);
The Network tab shows the script downloading. The Elements tab shows the script as the last child of the head element. Yet ko remains undefined.
The short version is that:
Asana uses an internal module system that uses module.exports and require - the CommonJS standard you may know from node.js.
The knockout.js file checks the environment to determine if it should be setting window.ko or using module.exports or AMD-style define. If it detects CommonJS-style require it sets properties on exports instead of on a global ko object.
Workaround:
You could temporarily "copy" require off first:
_require = require; require = null
And then it should set window.ko as you're expecting!

Categories

Resources