node.js - mocha testing ajax asynchronous request action error
高洛峰
高洛峰 2017-05-16 13:39:34
0
1
750

When mocha tests an asynchronous action with an ajax request, the console reports a Cannot read property 'document' of undefined error. The code is as follows:
/counter.js/

import $ from "../componet/jquery.min.js" export const CHANGE_USERNAME_ERROR = 'CHANGE_USERNAME_ERROR' export function checkUsername (name) { return (dispatch) => { $.get('/check', {username: name}, (msg) => { dispatch({ type: CHANGE_USERNAME_ERROR, error: msg }) }) } }

/counter.test.js/

import { expect } from 'chai' import sinon from 'sinon' import * as Actions from '../../public/javascripts/actions/counter'; describe('actions/register', () => { let actions let dispatchSpy let getStateSpy let xhr let requests beforeEach(function() { actions = [] dispatchSpy = sinon.spy(action => { actions.push(action) }) xhr = sinon.useFakeXMLHttpRequest() requests = [] xhr.onCreate = function(xhr) { requests.push(xhr); }; }) afterEach(function() { xhr.restore(); }); describe('Action: checkUsername', () => { it('Should call dispatch CHANGE_USERNAME_ERROR.', () => { Actions.checkUsername('foo@bar')(dispatchSpy) const body = '不能含有特殊字符' // 手动设置 ajax response requests[0].respond(200, {'Content-Type': 'text/plain'}, body) expect(actions[0]).to.have.property('type', Actions. CHANGE_USERNAME_ERROR) expect(actions[0]).to.have.property('error', '不能含有特殊字符') }) }) }) 报的是jquery.min.js中的错误,我是在控制台跑的mocha,麻烦各位给参谋参谋!拜谢
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all (1)
迷茫

First of all, you don’t have a DOM environment here, you need jsdom to simulate a DOM environment. Second, even if you simulate the DOM environment, you cannot call AJAX, because for your test, there is no server at all that can make requests for you, unless you simulate a mock server here, which I have not tried.

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!