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,麻烦各位给参谋参谋!拜谢
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.