用Jest进行React单元测试-关于模拟localStorage的问题

时间:2018-07-20 09:28:12

标签: reactjs redux jestjs enzyme

我在对一个简单组件进行单元测试时遇到了一个问题(这里甚至更简化了):

import React, { Component } from 'react';
import Logout from '../auth/Logout';
import { logoutUser } from '../../actions/auth';

export default class Navbar extends Component {

  render() {
    const { dispatch, isAuthenticated } = this.props;

    if (isAuthenticated) {
      logStatus = <Logout onLogoutClick={() => dispatch(logoutUser())} />;
    } else {
      logStatus = (
        <Link to="/login/">
          <Button>Login</Button>
        </Link>
      );
    }

    return (
      <AppBar>        
        {logStatus}
      </AppBar>
    );
  }
}

import { logoutUser } from '../../actions/auth';
中 我在localStorage上有一个removeItem函数。我不会在测试中使用它,但是那是我出错的地方。

我的测试是:

test('Navbar test series', () => {
  //Enzyme testing
  it('show the login button', () => {
    const wrapper = shallow(<Navbar isAuthenticated={true} />);
    expect(wrapper.find(Login)).to.have.length(1);
  });
});

我知道了:

ReferenceError: localStorage is not defined      
      at Object.<anonymous> (src/axios/axios.js:8:15) [I don't know why this is here...]
      at Object.<anonymous> (src/actions/auth.js:89:38) [my logoutUser using localStorage is here ]
      at Object.<anonymous> (src/components/UI/Navbar.js:3:13)
      at Object.<anonymous> (src/components/UI/Navbar.test.js:2:15)

按照此处How do I deal with localStorage in jest tests?的建议进行操作:

var localStorageMock = (function () { [...]})();
Object.defineProperty(window, 'localStorage', { value: localStorageMock });

没有帮助。

我不明白的是,我什至没有打电话给dispatch(logoutUser()),所以为什么要尝试访问localStorage?问题是由于通过调度进行的Redux造成的吗?

非常感谢您的帮助!

EDIT1: 注销组件:

import React from 'react';
import Button from '@material-ui/core/Button';

const Logout = props => (
  <Button onClick={() => props.onLogoutClick()}     color="secondary">LOGOUT</Button>
);

export default Logout;

以及来自action / auth.js和logoutUser()的代码:

export function logoutUser() {
  return dispatch => {
    dispatch(requestLogout());
    localStorage.removeItem('token');
    dispatch(receiveLogout());
  };
}

3 个答案:

答案 0 :(得分:1)

您可以添加测试文件

global.localStorage = {
    getItem: () => undefined,
};

test('Navbar test series', () => {
  //Enzyme testing
  it('show the login button', () => {
    const wrapper = shallow(<Navbar isAuthenticated={true} />);
    expect(wrapper.find(Login)).to.have.length(1);
  });
});

答案 1 :(得分:0)

您是否尝试过为该测试完全模拟../../actions/auth

jest.setMock('../../actions/auth', () => ({ logoutUser: jest.fn() }))

答案 2 :(得分:0)

所以解决方案在:

      at Object.<anonymous> (src/axios/axios.js:8:15) [I don't know why this is here...]

在运行时使用localstorage找到一个const的地方。只需将其置于状况中即可解决问题。

感谢所有的努力,这是我的错误:-(