gpt4 book ai didi

javascript - Redux 测试 - ReferenceError : localStorage is not defined

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:31:29 33 4
gpt4 key购买 nike

我目前在对我的 redux 操作运行测试时遇到了很多麻烦。测试通过,但每次运行时都会出现以下错误:

ReferenceError: localStorage is not defined

之前我也遇到过错误:

ReferenceError: fetch is not defined

我通过使用 isomorphic-fetch 解决了这个问题。无论如何,我不确定应该如何配置 Mocha 来运行这些前端测试。任何帮助将非常感激。


Mocha 测试命令:

mocha -w test/test_helper.js test/*.spec.js

test_helper.js:

require('babel-register')();
var jsdom = require('jsdom').jsdom;

var exposedProperties = ['window', 'navigator', 'document'];

global.document = jsdom('');
global.window = document.defaultView;

Object.keys(document.defaultView).forEach((property) => {
if (typeof global[property] === 'undefined') {
exposedProperties.push(property);
global[property] = document.defaultView[property];
}
});

global.navigator = {
userAgent: 'node.js'
};

documentRef = document;

auth.actions.spec.js

import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import * as actions from '../client/app/actions/auth'
import * as types from '../client/app/constants/ActionTypes'
import nock from 'nock'
import chai from 'chai'
import sinon from 'sinon'

var expect = chai.expect

import { SERVER_API } from './config'

const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)

describe('auth actions', () => {

afterEach(() => {
nock.cleanAll()
})

it('creates LOGIN_REQUEST and LOGINSUCCESS when correct username and password provided', () => {

nock(SERVER_API)
.post('/login', {
username: 'test',
password: 'password'
})
.reply(200, {
token: 'TOKEN'
});

const expectedActions = [
{
type: types.LOGIN_REQUEST,
isFetching: true,
isAuthenticated: false,
creds: {
username: 'test',
password: 'password'
}
},
{
type: types.LOGIN_SUCCESS,
isFetching: false,
isAuthenticated: true,
token: 'TOKEN'
}
]

const INITAL_STATE = {
isFetching: false,
isAuthenticated: false
}
const store = mockStore(INITAL_STATE)

return store.dispatch(actions.loginUser({username:'test',password:'password'}))
.then(() => {
expect(store.getActions()).to.deep.equal(expectedActions)
})
})
})

auth.js

import { push } from 'react-router-redux'
import 'es6-promise'
import fetch from 'isomorphic-fetch'

import {
LOGIN_REQUEST, LOGIN_SUCCESS, LOGIN_FAILURE
} from '../constants/ActionTypes.js'

import { SERVER_PORT } from '../constants/config'


function requestLogin(creds) {
return {
type: LOGIN_REQUEST,
isFetching: true,
isAuthenticated: false,
creds
}
}

function receiveLogin(user) {
return {
type: LOGIN_SUCCESS,
isFetching: false,
isAuthenticated: true,
token: user.token
}
}

function loginError(message) {
return {
type: LOGIN_FAILURE,
isFetching: false,
isAuthenticated: false,
message
}
}

export function loginUser(creds) {

let config = {
method: 'POST',
headers: { 'Content-Type':'application/x-www-form-urlencoded' },
body: `username=${creds.username}&password=${creds.password}`
}

return dispatch => {
dispatch(requestLogin(creds))
return fetch('http://localhost:'+SERVER_PORT+'/api/login', config)
.then(response =>
response.json()
.then(user => ({ user, response }))
).then(({ user, response }) => {
if (!response.ok) {
dispatch(loginError(user.message))
return Promise.reject(user)
}
else {
dispatch(receiveLogin(user))
localStorage.setItem('token', user.token) //offending line
dispatch(push('foo'))
}
}).catch(err => console.log("Error: ", err))
}
}

谢谢。

最佳答案

非常简单的错误,您不能在 mocha 测试中使用 localStorage,因为 window.localStorage 未定义。有两种方法可以解决这个问题。更“经典”的方法是从您的操作中移动 localStorage 调用,因为这是一种副作用,是 redux 操作中的反模式。相反,您应该使用中间件来捕获此操作并设置 localStorage

通过这样做,您已经消除了测试此操作的问题。

但是,如果您不知道该怎么做并且认为这样做不明智,那么您可以通过在 mocha 测试顶部创建一个全局变量来“伪造”localStorage创建一个伪造的 localStorage 的文件。我建议不要使用这个,但它绝对是适合您的情况的解决方案。

关于javascript - Redux 测试 - ReferenceError : localStorage is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37398427/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com