pnsrinivasreddy
pnsrinivasreddy

Reputation: 203

mocha enzyme global scoping issue

I am using mocha and enzyme to test my react components. I have an issue with global scoping (localStorage) in react components.

Foo.js

import React, { PropTypes } from 'react';

const propTypes = {};

const defaultProps = {};

class Foo extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
  localStorage.setItem("lastname", "Smith");
    return (
      <div className="foo"></div>
    );
  }
}

Foo.propTypes = propTypes;
Foo.defaultProps = defaultProps;

export default Foo;

Below is the code of unit testing of Foo component.

import React from 'react';
import { expect } from 'chai';
import { shallow, mount, render } from 'enzyme';
import Foo from '../src/Foo';

describe("A suite", function() {

  it("contains spec with an expectation", function() {
    expect(shallow(<Foo />).is('.foo')).to.equal(true);
  });

  it("contains spec with an expectation", function() {
    expect(mount(<Foo />).find('.foo').length).to.equal(1);
  });

});

When I run the test I am getting the below error.

ReferenceError: localStorage is not defined

seems like this error occurring when global objects like localStorage exists component render method.

Does it have any solution??

Upvotes: 2

Views: 451

Answers (1)

Webb Lu
Webb Lu

Reputation: 328

The mocha testing suite is running under the node.js environment, not the browser, and the localstorage is existing in browser only, not existing in node.js,

So you need to use some package to simulate localstorage in nodejs

Try this npm package: https://www.npmjs.com/package/dom-storage

install this package by npm first

npm i dom-storage -D

then adding these code below in the Foo.js

if( typeof window === undefined ){
    const Storage = require('dom-storage')
    const localStorage = new Storage('./db.json', { strict: false, ws: '  ' })
}

then every thing you set by setItem() will store into the db.json

if you want keep the original localStorage when the code is running on browser

Upvotes: 0

Related Questions