- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我目前在对我的 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/
我是 Angular 新手。使用 $localstorage(ngStorage) 是否有任何特定的原因而不是常规的 javascript localstorage 有什么区别。 谁能给我解释一下吗?
这个问题说明了一切。我意识到所有选项都可以在最新的浏览器中使用,但是语义上最好的选择是什么?为什么? 最佳答案 根据 W3C 标准,正确的是 window.localStorage,因为 localS
我想不出一个好的标题,所以希望可以。 我正在做的是创建一个离线 HTML5 webapp。 “出于某些原因”我不希望将某些文件放在缓存 list 中,而是希望将内容放在 localStorage 中。
我最近问了a question about LocalStorage .使用 JSON.parse(localStorage.item) 和 JSON.parse(localStorage['item
我最近问了a question about LocalStorage .使用 JSON.parse(localStorage.item) 和 JSON.parse(localStorage['item
我最近问过a question about LocalStorage 。使用 JSON.parse(localStorage.item) 和 JSON.parse(localStorage['item
我在将本地存储的定价添加到其他字段时遇到问题。如果我将 beforeNoonNPSlot 的价格设置为 2,但我将 matineeNPSlot 的字段留空(它应该保留分配给的任何价格)最后)。然后在我
我需要从 localStorage 对象变量中删除对象键而不从 localStorage 中删除键 let obj = localStorage; let keys = Object.keys(loc
根据我所读到的内容,我希望以下代码能够工作。 此代码是函数的一部分,该函数应该通过用下一个更高的 localStorage 变量覆盖它来删除 localStorage 变量。一旦没有更多内容可供复制,
这个问题已经有答案了: 已关闭10 年前。 Possible Duplicate: JavaScript property access: dot notation vs. brackets? 我是
编写localStorage['key'] = value或localStorage.setItem('key', value)有区别吗? 我看到了this question标记为重复,但在开发人员工
我一直在做以下事情: var store = window.localStorage; store.setItem() 但现在我看到代码是这样做的: localStorage.setItem() 两者
我在 Chrome 上遇到此错误。不知道为什么会发生。任何帮助!我正在使用 Backbone.localStorage 插件和 Backbone。我在以下行中收到错误: localStorage: B
如果我尝试以下代码: var c = new Backbone.Collection(); c.localStorage = new Backbone.LocalStorage("items");
我想使用 localStorage 存储用户输入值,然后在倒计时器中使用该值。 这是用户输入数据的 HTML: Work Time
我有一个适用于 Mac 和 Linux 用户但不适用于 Windows 用户的 Chrome 扩展程序。当我进入控制台并在 localStorage 中设置一个项目时,它工作正常,但是当用户尝试使用扩
在这里浏览所有问题/答案,但找不到解决我的问题的方法。条件('localStorage' in window)返回 true但是 localStorage 的对象本身仍然是 undefined . 设
使用下面的代码,我创建一个 localstorage 变量,如果未定义,则其键为 quote = 1。然而,当最终使用相同的引号键再次调用它时,即使使用了 Number() 函数,它也会变成 11 而
我上次检查时,以下两行返回 true: null == localStorage["foo"]; null == localStorage.getItem("foo"); 将 null 替换为 und
我正在尝试在 NextJS 静态站点上使用 localStorage,但遇到 localStorage 未定义错误。 我的错误显示组件的代码是: export default function Cat
我是一名优秀的程序员,十分优秀!