mongoose와 express 기반의 프로젝트에서 jest를 사용해 Back-end API의 통합 테스팅을 하고자 한다.
point.test.js
const request = require("supertest")
const app = require("../app") 
describe("Temp test", () => {
  it("testing test", async () => {
    const response = await request(app).get("/points")
    console.log(response.status)
    expect(true).toBe(true)
  })
})
app.js
... // `express generator` 라이브러리를 통해 기본 구조 생성
mongoose
  .connect(process.env.MONGO_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => console.log("Successfully connected to mongodb"))
  .catch(e => console.error(e))
테스팅을 시작하면, 테스트 결과에 상관없이 다음과 같은 오류가 발생한다.
npm run test // "test": "jest --watchAll"
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.
      at BufferList.Readable (node_modules/readable-stream/lib/_stream_readable.js:179:22)
      at BufferList.Duplex (node_modules/readable-stream/lib/_stream_duplex.js:67:12)
      at new BufferList (node_modules/bl/bl.js:33:16)
      at new MessageStream (node_modules/mongodb/lib/cmap/message_stream.js:35:21)
      at new Connection (node_modules/mongodb/lib/cmap/connection.js:52:28)
/Users/kimhyeji/Desktop/scookie_server/node_modules/readable-stream/lib/_stream_readable.js:111
  var isDuplex = stream instanceof Duplex;
                        ^
TypeError: Right-hand side of 'instanceof' is not callable
    at new ReadableState 
    ...
You are trying to `import` a file after the Jest environment has been torn down.
이 오류를 찾아 헤매다보면 가장 많이 보이는 해결책이 jest.useFacTimers()이다.
그러나 에러는 여전히 존재했고 구글의 그 어느곳에도 명확한 해결책은 없었다.
혼자서 해결하려고 용쓰다보니 사고가 막힌 것 같아 팀원들에게 도움을 청했다.
같이 얘기하다 보니까, app.js에서 mongoDB가 연결되었다면 나와야 할 콘솔로그가 찍히지 않았단 사실을 깨달았다. 🥺
app.js
mongoose
  .connect(process.env.MONGO_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => console.log("Successfully connected to mongodb")) // <- 이거
  .catch(e => console.error(e))
app.js의 moongoose.connect하는 부분이 안끝났기 때문에 발생했을 것이다.app.js를 import하지 않으면 저 에러가 발생하지 않는다.app.js import를 제외하고, 코드로 인해 발생할 모든 경우를 확인해봤지만 문제없었다.test 환경변수 추가NODE_ENV !== "test"일 때만 app.js에서 DB연결을 시도하게끔 한다.
package.json
"test": "cross-env NODE_ENV=test jest --watchAll"
app.js
if (process.env.NODE_ENV !== "test") {
  mongoose
    .connect(process.env.MONGO_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })
    .then(() => console.log("Successfully connected to mongodb"))
    .catch(e => console.error(e))
}
테스팅을 시작하기 전에 DB 연결을 하도록 beforeAll를 사용해 수정한다.
point.test.js
const mongoose = require("mongoose")
const request = require("supertest")
const app = require("../app")
describe("Temp test", () => {
  beforeAll(async () => {
    await mongoose
      .connect(process.env.MONGO_URI, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
      })
      .catch(e => console.error(e))
  })
  it("testing test", async () => {
    const response = await request(app).get("/points")
    console.log(response.status)
    expect(true).toBe(true)
  })
})
Jest는 본래 React 어플리케이션을 위한 테스팅 도구이다. 따라서 Node.js에서 사용하기 위해서 몇 가지 유의할 사항이 있다. 위 링크를 통해 꼭 읽어보고 mongoDB를 사용하는 프로젝트에 jest를 알맞게 도입하도록 하자.