简体   繁体   English

Mocking 和 function 在 Jest 单元测试的明确请求中

[英]Mocking a function within an express request for a Jest Unit test

I have a simple express application and i want to fully be able to mock it, here's what i've got so far我有一个简单的快速应用程序,我希望完全能够模拟它,这就是我到目前为止所拥有的

userRoute.js

const express = require("express")
const router = express.Router()
const db = require('./db')

router.get("/users/", async (req, res) => {
  res.json({
    status: 200,
    data: await db.getUsers(),
  })
})

module.exports = router

My issue is i am trying to mock the db.getUsers function but not sure how我的问题是我试图模拟db.getUsers function 但不确定如何

here is my test code:这是我的测试代码:

const router = require("./userRoute.js")

const app = new express()
app.use("/", router)

describe("Users Route", () => {
  test("getUsers Happy Path", async () => {
    jest.spyOn(db, "getUsers").mockImplementation(() => {
      return {
         id:12345
         name: "Jason"
         age: "34"
       }
    })

    const res = await app.get("/users/")
    console.log(res)
  })
})

this doesn't work for me, if i run the function regularly in a standard function it works but since its an api endpoint in a route it doesn't work for whatever reason, any help would be fantastic这对我不起作用,如果我在标准 function 中定期运行 function 它可以工作,但由于它是一个 api 端点,无论出于何种原因,它都不会因为任何工作原因而非常棒,

Maybe you want to try to mock the db before require the useRouter.js也许您想在需要useRouter.js之前尝试模拟数据库

Also, you need to run the server (and close it after all tests) and make a real request to your server.此外,您需要运行服务器(并在所有测试后关闭它)并向您的服务器发出真正的请求。

const express = require('express');
const axios = require('axios');
const PORT = 5565;

const userMock = {
  id: 1,
  name: 'John Doe',
  email: 'email@email.com',
}
const dbSpy = jest.spyOn(require('./db.js'), 'getUsers').mockImplementation(() => userMock);

const router = require('./index.js');

const app = express();

app.use('/', router);

const server = app.listen(PORT, () => 'Example app listening on port 3000!');

describe('Users Route', () => {
  afterAll(() => server.close());
  test('getUsers Happy Path', async () => {
    const response = await axios.get(`http://localhost:${PORT}/users/`);      

    expect(dbSpy).toHaveBeenCalledTimes(1);
    expect(response.status).toBe(200);
    expect(response.data.data).toEqual(userMock);
  });  
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM