を返しました:私はVueのは、非同期的にサーバーからデータを取得することをテストしたいVue.js - テストは、非同期Iは、次の例持つデータ
<!DOCTYPE html>
<html>
<head>
<title>Mocha</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="mocha.css" />
</head>
<body>
<div id="mocha"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/3.1.2/mocha.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.5.0/chai.min.js"></script>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.0.3/vue-resource.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/1.15.4/sinon.js"></script>
<script>mocha.setup('bdd');</script>
<script>
"use strict";
var assert = chai.assert;
var should = chai.should();
var vm = new Vue({
data: {
message: "Hello"
},
methods: {
loadMessage: function() {
this.$http.get("/get").then(
function(value) {
this.message = value.body.message;
});
},
}
});
describe('getMessage', function() {
let server;
beforeEach(function() {
server = sinon.fakeServer.create();
});
it("should get the message", function(done) {
server.respondWith([200, { 'Content-Type': 'application/json' },
JSON.stringify({message: "Test"})]);
vm.message.should.equal("Hello");
vm.loadMessage();
server.respond();
setTimeout(function() {
// This one works, but it's quirky and a possible error is not well represented in the HTML output.
vm.message.should.equal("Test");
done();
}, 100);
// This one doesn't work
//vm.message.should.equal("Test");
});
});
</script>
<script>
mocha.run();
</script>
</body>
</html>
を。しかし、私はSinon FakeServerで実際のHTTPリクエストを模擬しています。
もちろん、loadMessage
を呼び出した直後にメッセージが設定されていません。私はテストにタイムアウト機能を使うことができましたが、もっと良い方法があるはずです。私はrespondImmediately
を調べましたが、変更されませんでした。また、done()関数を呼び出す可能性もあります。しかし、これを理解すると、これはloadMessage
関数内で呼び出される必要があり、したがってテスト対象のコードを変更する必要があります。
この問題を解決する正しい方法は何ですか?
編集:私は、少なくとも部分的な解決策を見つけましたが、それはまだ乱雑であるようです。mochaユニットテストでdone()関数を呼び出します。アサーションが失敗すると、少なくともhtml出力に表示されます。しかし、アサーションメッセージは、通常のテストの場合ほど明確ではありません。また、この技術はまだ私には面倒なようです。 VUEコンポーネントの更新が非同期に行われるため
より良い回答が得られない場合は、インターセプタを見てください。https://github.com/pagekit/vue-resource/blob/master/docs/http.md#interceptors – Hammerbot
'loadMessage'が返すもの? –
loadMessageは何も返さず、ビューモデルで定義されます。サーバーからデータを非同期的にロードし、メッセージの受信時にモデルを更新します。 –