apigee-127 / swagger-tools

A Node.js and browser module that provides tooling around Swagger.
MIT License
701 stars 374 forks source link

Is there an example of how to use supertest with swagger-tools? #634

Open vomc opened 2 years ago

vomc commented 2 years ago

Hi,

I am looking to set up a full integration test of an API that is running on this library and the other (potentially outdated swagger-express-mw) library. I found a bunch of misc threads on GH (https://github.com/apigee-127/swagger-tools/issues/495) regarding testing but have not found any comprehensive examples of how to use supertest with this library.

Reading through some of these threads it seems that one of the issues is that you must wait for swaggerMw to initialize and then export your app async so you can use it in tests. I solved this by creating a wrapper in the form of:

async function init() {
    return new Promise((resolve, reject) => {
        SwaggerExpress.create(swaggerConfig, function (err, swaggerExpress) {
                 // set up 100 lines of various middleware with app.use()
                 // then
                 resolve(app)
}

I export this function and then wanted to use it in my jest test like so:


const init = require('../../../src/app')

describe('foo', () => {
  it('bar', () => {
    // use init
    init().then(app => {
       // use app in supertest
      request(app).... // do some stuff
    })
  })
})

However, it seems that what happens is that the second I require the app (const init = require('../../../src/app')), my entire test crashes with

      at node_modules/swagger-node-runner/node_modules/swagger-tools/index.js:126:17
      at cbWrapper (node_modules/swagger-node-runner/node_modules/swagger-tools/lib/specs.js:1035:5)
      at validateSwagger2_0 (node_modules/swagger-node-runner/node_modules/swagger-tools/lib/specs.js:1030:3)
      at validateSemantically (node_modules/swagger-node-runner/node_modules/swagger-tools/lib/specs.js:1040:5)
      at node_modules/swagger-node-runner/node_modules/swagger-tools/lib/specs.js:1233:7
      at node_modules/swagger-node-runner/node_modules/swagger-tools/lib/specs.js:1073:29
      at node_modules/swagger-node-runner/node_modules/swagger-tools/lib/specs.js:719:12
      at node_modules/swagger-node-runner/node_modules/swagger-tools/lib/specs.js:695:9
  console.error
    Error initializing middleware

And I get an error about Cannot find module '/myapp/src/api/fittings/swagger_router' from 'node_modules/bagpipes/lib/fittingTypes/user.js'

Any ideas what might be causing this? I am not sure what fittingTypes and user.js is or where they come from...