2017-01-06 8 views
1

私のクライアント側のAPIの使用方法は、karmaMochaSinoです。しかし、私は非同期プロセスを取得するつもりです。何らかの理由で非同期のajax呼び出しによるSinon/Mochaテストで約束が返されない

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(); 
}); 

}); 

、私はいつもMochaからError: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.を取得。 axios.get()が実行されていないのでthenのように見えるので、doneも呼び出されません。

私は、私はここで何かを

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(); 
     }); 
    }); 
    }); 
}); 

Mocha文書で推奨されたものをフォローをしていたのですか?ありがとうございました

答えて

1

open issue on sinonここにあるような斧では動作しないと言われます。

Axiosは実際にあなたの偽装サーバーを呼び出すわけではありません。それは文字通り/cartを要求しようとしているようです。そのためタイムアウトが発生します。

ユーザーがanother lib called nockでfakeServerを交換し、彼mentions it here

あなたが要求を模擬することができ、他のLIBSがあります。

私は通常supertest npmGithubを使用します。問題は非常に有用だった

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; 
    }); 
+0

のGithubのREADMEから

例は、夫婦の時間を過ごします。しかし、少なくとも私は愚かではないことを知っています... hah –

+0

@IanZhao彼らはaxishにはリクエストを模倣する 'moxios'と呼ばれるlibがあるという問題についても言及しています。https://github.com/mzabriskie/moxios – BrunoLM

関連する問題