joneshf / purescript-webstorage

6 stars 9 forks source link

Test runner fails with `window is not defined` #13

Open dbaynard opened 6 years ago

dbaynard commented 6 years ago

Hello,

Introducing webstorage has caused my test suite to fail. I suspect the solution is fairly simple (simulating a window in node), but it isn't documented with this library, and it isn't obvious how to do it in purescript (I'm yet to figure it out).

It's caused (I think) by

https://github.com/joneshf/purescript-webstorage/blob/b7558d677a81430ecbd9d160c293663a3b59a971/src/Browser/WebStorage.js#L3-L4

The error:

* Build successful.
* Running tests...
$PROJECT/output/Browser.WebStorage/foreign.js:3
exports.localStorage = window.localStorage;
                       ^

ReferenceError: window is not defined
joneshf commented 6 years ago

Sorry about that.

You're right, this is a browser only package. I won't prescribe a fix because I don't know the best way to fix it, but the fix is the same how you'd fix it if you were writing plain JS and you brought in some JS dependency that was browser only.

it isn't documented with this library

What's a good way to communicate that you should only be using this package in a browser? I don't plan to make a code change to allow using this on node or anything, but I'm more than willing to document that it's browser only. Given that you've run into this, I figure your thoughts on communicating the requirements are better than mine.

dbaynard commented 6 years ago

How about documenting the foreign import data WEB_STORAGE :: Effect line so it shows up in the pursuit documentation, there?

-- | Requires a `window` object, usually provided by a browser. 
foreign import data WEB_STORAGE :: Effect

if you were writing plain JS and you brought in some JS dependency that was browser only

I'm not sure how to integrate it with pulp test… that's not an issue for this library, though.

dbaynard commented 6 years ago

OK, I had to come back to this, and found a solution. It's actually quite simple — once I'd worked out which node library actually did what I wanted, the purescript implementation took a matter of minutes.


  1. Run the following to add a mocking library (other libraries are available) to npm devDependencies (or equivalent).
> npm install --save-dev mock-local-storage
  1. Add the following line into test/Main.purs
foreign import mockStorage :: forall eff . Eff eff Unit
  1. Add a file test/Main.js with the following contents (or combine the following with an existing test/Main.js)
"use strict"

global.window = {};
const localStorage = require('mock-local-storage');
window.localStorage = global.localStorage;

exports.mockStorage = function() {
    return window;  
}