Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...