Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QUnit issues with document.cookie

I'm writing a unit test on a javascript class that handles all the cookies manipulation in my code. It basically sets and retrivies cookies using document.cookie

I'm having an issue while writing this unit test as document.cookie in my unit test always returns empty string.

I even tried putting a debugger statement in my unit test, and then in the browser console I tried this.

    document.cookie = "name=oeschger;"

Even after that in browser console when I typed document.cookie it is an empty string. What is going on here?

like image 538
sublime Avatar asked Aug 29 '26 23:08

sublime


1 Answers

The root of this problem is that when you're loading a webpage from your filesystem (e.g., file:///) cookies won't work correctly. This is because cookies are tied to a host and when you're working off the filesystem you don't really have a host. If you open the test file hosted through a web server instead, you'll see that the cookies work correctly. You can run a simple web server with this command from the project directory:

python -m SimpleHTTPServer 8080

I had the exact same problem building an object that helps me manipulate cookies as part of an open source JS project I'm working on, Sprinkles. Unfortunately, I'm able to see the tests pass in the browser but not via grunt.

like image 155
Avand Amiri Avatar answered Aug 31 '26 14:08

Avand Amiri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!