Why does npm test return TypeError: app.use() requires a middleware function when server gets passed to it?

Why does npm test return TypeError: app.use() requires a middleware function when server gets passed to it?

我正在尝试为我的后端编写一些简单的测试,并且我正在遵循一个非常相似的代码功能的教程,而我的却没有(他没有抱怨他的 app.use())。为什么会抛出 TypeError: app.use() 需要一个中间件函数,我可以用什么来替换我当前的代码以使其进入 运行 我的测试?

这是我的代码:

const express = require('express');
const request = require('supertest');
const app = express();

const api = require('../server');

// make api available
app.use(api);
//app.use(bodyParser);

describe('games', () => {
    it('should return a saved game', () => {
        // send a request
        return request(app)
            .post('/games')
            .send({title: 'test', released: '1995'})
            // verify response
            .expect(201)
            .expect(res => {
                const game = res.body;
                expect(game.title).toEqual('test');
                expect(game.released).toEqual('1995');
            });
    });
});

这是来自控制台的错误:

"C:\Program Files\nodejs\node.exe" C:\Users\Bertinator\Desktop\web-exam\node_modules\react-scripts\scripts\test.js --colors --setupTestFrameworkScriptFile "C:\Program Files\JetBrains\IntelliJ IDEA 2017.2.4\plugins\JavaScriptLanguage\helpers\jest-intellij\lib\jest-intellij-jasmine.js" --testPathPattern ^C:\Users\Bertinator\Desktop\web\-exam\src\backend\__tests__\game\.jest\.js$
 FAIL  src\backend\__tests__\game.jest.js
  ● Test suite failed to run

    TypeError: app.use() requires a middleware function

      at Function.use (node_modules/express/lib/application.js:210:11)
      at Object.<anonymous> (src/backend/__tests__/game.jest.js:10:5)
          at <anonymous>

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.761s

我通过添加

修复了它
module.exports = app;

致我的server.js。 Jest 无法将其用作有效的中间件,因此出现错误。

app.use() 至少需要 2 个参数,url 和中间件。我看不到 ../server/ 的内容,所以无法给出建议。

要真正提供一个好的答案,您应该显示 ../server 的内容。