SuperTest - 应用未定义

SuperTest - App is not defined

我是测试驱动开发的新手,正在尝试使用 supertest 自学。我很困惑为什么我总是收到错误 "app is not defined"?这是我对 request(app) 的调用,我在下面加粗了。我试图查找文档,但似乎没有太多。我所有的路线都在一个名为 "middleware" 的文件中,该文件的开头如下:

 var bodyParser = require('body-parser');
    var helpers = require('./helpers.js'); // our custom middleware
    var db = require('../DB/DB.js');
    var router = require('../routes.js');
    var path = require('path');
    var fs = require('fs');
    var gm = require('gm');


    module.exports = function (app, express) {}

我使用 supertest 测试中间件文件路由的实际文件:

    var chai = require('chai')
    var assert = chai.assert;
    var should = chai.should();
    var expect = chai.expect;
    var helpers = require("../config/helpers.js");
    var middleware = require("../config/middleware.js");
    // for when we eventually want to test against mock data
    var fs = require('fs');
    var path = require('path');
    var supertest = require("supertest")(middleware);

describe('middleware API', function() {


  it('responds with binary data', function(done) {
    var imagePath = path.join(__dirname, '/../assets/drawings/', userName + '.png');
    **request(app)**
      .get(imagePath)
      .expect(201)
      .expect('Content-Type', 'image.png')
      .parse(binaryParser)
      .end(function(err, res) {
        if (err) return done(err);

        // binary response data is in res.body as a buffer
        assert.ok(Buffer.isBuffer(res.body));
        console.log("res=", res.body);

        done();
      });
  });

  it('sends back one image', function(done) {
    **request(app)**
      .get('/game/')
      .expect(201)
      .expect('Content-Type', 'image.png')
      .expect('Content-Length', '1')
      .parse(binaryParser)
      .end(function(err, res) {
        if (err) return done(err);

        // binary response data is in res.body as a buffer
        assert.ok(Buffer.isBuffer(res.body));
        console.log("res=", res.body);

        done();
      })

  })
})

在文件的顶部,您需要定义 express 和 app,即:

var express        = require('express'),
    app            = express();

此外,请确保您已经安装了 express,即通过节点中的命令行:

npm install express --save

(使用“--save”将其添加到您的 package.json 文件中,这样可以轻松跟踪版本等,但如果其他人使用 npm install 安装您的项目,也会自动安装) .