使用异步ajax调用的Sinon / Mocha测试没有返回promise [英] Sinon/Mocha test with async ajax calls didn't return promises

查看:110
本文介绍了使用异步ajax调用的Sinon / Mocha测试没有返回promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的客户端api使用 karma 编写一些测试,其中 Mocha 。但我仍然坚持要获得异步过程。

I'm writing some test for my client side api use karma with Mocha and Sino. But I'm stuck on getting the async process.

import api from '../../../src/api';
import stubData from '../data';
import axios from 'axios';

/* eslint-disable prefer-arrow-callback,func-names */
describe('API test', function () {
  before(function () {
    this.server = sinon.fakeServer.create();
  });
  after(function () {
     this.server.restore();
  });

it('Should return cart with provided token', function (done) {
  this.server.respondWith("GET", "/cart",
        [200, { "Content-Type": "application/json" },
         '[{ "id": 12, "comment": "Hey there" }]']);

 axios.get('/cart')
  .then(function (response) {
    console.log(response);
    done();
  })
  .catch(function (error) {
    console.log(error);
    done();
  });
  this.server.respond();
});

 });

出于某种原因,我总是得到错误:超出2000ms超时。对于异步测试和挂钩,确保调用done();如果返回Promise,请确保它已解析。来自 Mocha 。似乎然后 axios.get()之后没有被执行因此已完成也没有被调用。

for some reason, I always getting Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. from Mocha. Seems like the then after axios.get() is not executed thus done is not called either.

我确实按照 Mocha 文件中推荐的内容

I did follow what was recommended in Mocha document

describe('User', function() {
  describe('#save()', function() {
    it('should save without error', function(done) {
      var user = new User('Luna');
      user.save(function(err) {
        if (err) done(err);
        else done();
      });
    });
  });
});

我在这里做错了吗?谢谢

Am I doing anything wrong here? Thank you

推荐答案

似乎有对sinon开放问题说它不适用于axios,这似乎就是这种情况。

It seems there is an open issue on sinon saying it doesn't work with axios, which seems to be the case here.

Axios实际上并没有调用你的假服务器。它似乎试图从字面上请求 / cart ,这就是你超时的原因。

Axios is not actually calling your fakeserver. It seems to be trying to request /cart literally, that is why you get a timeout.

该用户被替换伪造的服务器与另一个名为nock的lib 在这里提及

That user replaced the fakeServer with another lib called nock he mentions it here

有其他允许你模拟请求的库。

There are other libs that allow you to mock requests.

我通常使用 supertest npm Github

来自Github README的示例

Example from Github README

var request = require('supertest');
var express = require('express');

var app = express();

app.get('/user', function(req, res) {
  res.status(200).json({ name: 'tobi' });
});

request(app)
  .get('/user')
  .expect('Content-Type', /json/)
  .expect('Content-Length', '15')
  .expect(200)
  .end(function(err, res) {
    if (err) throw err;
  });

这篇关于使用异步ajax调用的Sinon / Mocha测试没有返回promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆