客户端异步函数测试
以获取位置为例: 项目用到 mocha, chai, karma, 参考 前面 karma 配置
和前面一样新建目录
src
test
配置 karma
因为浏览器中运行不能使用 require,module
- 新建测试文件 fetch_test.js
describe('async-local test ',function(){
it('should pass this test',function(){
expect(true).to.eql(true);
});
it('should get lat and long from ',function(done){
let onSuccess = function(local){
expect(local).to.have.prototype('lat');
expect(local).to.have.prototype('lon');
done();
}
let onError = function(err){
throw 'not expected';
}
this.timeout(10000);
fetchLocal(onSuccess, onError);
});
});
- 新建被测试文件 fetch.js
let fetchLocal = function(onSuccess, onError) {
let returnLocal = function(position) {
let local = {
lat: position.coords.latitude,
lon: position.coords.longitude
};
onSuccess(local);
};
navigator.geolocation.getCurrentPosition(returnLocal, onError);
}
- 运行测试
npm test
# 获取位置通知我允许了,可是我本地出现错误,可能 API 获取位置失败了
Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
.