目標はAPIテストを記録することです。このテストは統合テストの一種で、すべてのミドルウェアでアプリケーション全体を読み込み、外部のhttp呼び出しを傍受して記録します。nodejs expressアプリですべてのリモート呼び出しをテスト用に記録する
Pythonの世界では、 "WebTest"と "VCRPY"があります。
アプリ:
'use strict';
const express = require('express');
const request = require('superagent');
var app = express();
app.get('/hammer/version', function(req, res) {
request
.get('http://httpbin.org/get')
.end(function(err, response) {
console.log(response.body);
res.status(200).json({
version: '0.1.0',
url: response.body.url
});
});
});
module.exports = app;
テスト:
/* global describe, it */
'use strict';
const request = require('supertest');
const app = require('./app.js');
var path = require('path');
var tape = require('tape');
var tapeNock = require('tape-nock');
// call tapeNock with tape and an options object
var test = tapeNock(tape, {
fixtures: path.join(__dirname, 'fixtures')
});
describe('Version test', function() {
this.timeout(0);
it('test version', function(done) {
test('record_version.json', function(t) {
request(app)
.get('/hammer/version')
.expect(200, {
url: "http://httpbin.org/get",
version: '0.1.0'
})
.end(function(err, res) {
if (err) return done(err);
t.end();
done();
});
});
});
});
"package.json":
{
"name": "remote_node_test",
"version": "1.0.0",
"description": "",
"main": "app.js",
"dependencies": {
"express": "^4.14.0",
"mocha": "^3.2.0",
"nock": "^9.0.2",
"superagent": "^3.3.1",
"supertest": "^2.0.1",
"tape": "^4.6.3",
"tape-nock": "^1.4.0"
},
"devDependencies": {
"mocha": "^3.2.0"
},
"scripts": {
"test": "mocha"
},
"author": "",
"license": "ISC"
}
テストは "モカ" で実行されています
NOCK_BACK_MODE=record node_modules/mocha/bin/mocha
最初に実行され、2回目の実行で「ロックダウン/レコード」が機能しません。
エラー:録画
% NOCK_BACK_MODE=lockdown node_modules/mocha/bin/mocha test.js :(
Version test
TAP version 13
# details.json
1) return current version
0 passing (32ms)
1 failing
1) Version test return current version:
TypeError: Cannot read property 'status' of undefined
at Test._assertStatus (node_modules/supertest/lib/test.js:263:10)
at Test._assertFunction (node_modules/supertest/lib/test.js:281:11)
at Test.assert (node_modules/supertest/lib/test.js:171:18)
at Server.assert (node_modules/supertest/lib/test.js:131:12)
at emitCloseNT (net.js:1553:8)
at _combinedTickCallback (internal/process/next_tick.js:71:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
は、すべての要求ですが、私は私の内部ロジックを「記録/モック」「外部」の要求を記録し、予防するためにのみ必要です。
参考までに、最新の 'tape-nock'を使用するようにサンプルを更新しました。これは、物事をより良くするいくつかの新機能(defaultTestOptionsとデフォルトのフィクスチャディレクトリ)を使用しています。 https://github.com/Flet/tape-nock-with-supertest-example – Flet