我在測試反應組件時遇到問題,該組件使用localstorage保存JWT令牌並根據身份驗證爲api調用和路由檢索它。React Testing - TypeError:localStorage.getItem不是函數
組件本身工作正常,但是當我測試,我在所有三個測試
TypeError: localStorage.getItem is not a function
這裏得到這個錯誤是我寫
home.test.js代碼
import React from 'react';
import { shallow, mount } from 'enzyme';
import { expect } from 'chai';
import sinon from 'sinon';
import Home from '../containers/Home.jsx';
describe('<Home />',() => {
beforeAll(() => {
global.localStorage = {
i2x_token: 'someToken',
};
});
it('renders without exploding',() => {
shallow(<Home />);
});
it('renders children when passed in',() => {
const wrapper = shallow(
<Home>
<div className='unique' />
</Home>,
);
expect(wrapper.contains(<div className='unique' />)).to.equal(true);
});
it('calls componentWillMount',() => {
sinon.spy(Home.prototype, 'componentWillMount');
const wrapper = mount(<Home />);
expect(Home.prototype.componentWillMount).to.have.property('callCount', 1);
Home.prototype.componentWillMount.restore();
});
});
home.jsx
import React, { Component } from 'react';
import { browserHistory } from 'react-router';
import Header from '../components/Header.jsx';
import Content from '../components/Content.jsx';
import { API_CONTENT } from '../utils/constants';
import request from '../utils/request';
class Home extends Component {
constructor(props) {
super(props);
this.state = {
content: null,
};
this.logout = this.logout.bind(this);
}
componentWillMount() {
const token = localStorage.getItem('i2x_token');
const requestURL = API_CONTENT;
const requestObj = {
method: 'GET',
headers: new Headers({
Authorization: `JWT ${token}`,
}),
};
request(requestURL, requestObj).then((reply) => {
if (reply.results.length > 0) {
this.setState({ content: reply.results });
} else {
console.log('no reply from API');
}
});
}
logout() {
localStorage.removeItem('i2x_token');
browserHistory.push('/');
}
render() {
const data = this.state.content;
if (data !== null) {
return (
<div className='container'>
<Header logout={ this.logout } />
<Content data={ this.state.content } />
</div>
);
}
return (
<div className='container'>
<Header logout={ this.logout } />
</div>
);
}
}
export default Home;
您也可以嘗試實現自己的localStorage的單元測試,並在一些設置的測試文件添加到全局或使用sinon.spy(因爲你已經爲componentWillMount做)嘲笑getItem函數 –
好吧,setItem會是什麼樣子? – rizvified
下面是一個例子:https://gist.github.com/sanusart/c1558845350cc8d8cafbe3c903d46afc –