mocha測試帶有ajax請求的非同步action時控制台報Cannot read property 'document' of undefined錯誤,程式碼如下:
/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,麻烦各位给参谋参谋!拜谢
首先,你這裡面沒有DOM環境,需要jsdom去模擬一個DOM環境。第二,就算你模擬了DOM環境,你也呼叫不了AJAX,因為對於你這個測試而言,壓根沒有伺服器可以給你呼叫請求,除非你在這裡又模擬一個mock伺服器,這個我沒試過。