搜索

首页  >  问答  >  正文

node.js - mocha测试ajax异步请求的action错误

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,麻烦各位给参谋参谋!拜谢
高洛峰高洛峰2752 天前847

全部回复(1)我来回复

  • 迷茫

    迷茫2017-05-16 13:41:34

    首先,你这里面没有DOM环境,需要jsdom去模拟一个DOM环境。第二,即便你模拟了DOM环境,你也调用不了AJAX,因为对于你这个测试而言,压根没有服务器可以给你调用请求,除非你在这里又模拟一个mock服务器,这个我没试过。

    回复
    0
  • 取消回复