簡體   English   中英

mocking 數據庫調用 api 路由

[英]mocking database calls in api routes

我正在使用 NextJS 和 MySQL 數據庫構建一個完整的堆棧應用程序。在我的 API 路由中,我調用了這個數據庫(例如, createOne()用於在數據庫中創建一個實例)。 當我使用 jest 運行我的測試時,我想模擬這個調用,這樣實際的 createOne() 就不會運行,而只是測試以便調用它。 據我所知,使用模擬是可能的,但我的測試仍然使用真實的 function 運行。

庫/數據庫.js

const createConnection = async () => {}; // creates the connection
export const createOne = async (instance) => {}; // inserts the instance to the database

頁面/api/index.js

import { createOne } from 'lib/database';
const handler = () => {
  ... // validation, creating the instance to insert etc.
  const id = await createOne(instance); // <-- this I don't want to be run when testing
  res.status(201).json({id, ...instance});
};
export default handler();

__tests__/api/index.js

import handler from 'pages/api/index';
import { createOne } from 'lib/database'; 
// I struggle how to structure the mock implementation here
beforeAll(() => {
  const createOne = jest.fn(); // ?
});
...
test(async () => {
  ... // setup req, res object
  await handler(req, res);
  // I have tests for the API logic, but it currently calls the database every time, which I don't want to.
  expect(createOne.mocks.calls.length).toBe(1); // here I get 0
});

我真的不知道我在哪里做錯了,我一直在搜索很多,但大多數例子只是 mocking 模塊,如axios等。

你好像不是mocking function...

看看下面,看看它是否有效......

  // mock function
    const createOneMock = jest.fn().mockImplementation(async (val) => 1)
    
    // Mock the module
    jest.mock("../lib/database", () => {
      return createOneMock
    })
    const handler = require("../index")
    
    test('my test', async () => {
      var req = {}
      var res = {}
      const rc = await handler(req, res);
      expect(rc).toBe(1)
      expect(createOneMock.mock.calls.length).toBe(1)
    })

ps:我是用Node來測試的,不管你用不Node,概念應該是一樣的。

我讓它工作的方式是開玩笑模擬 esModules 所需的一些解決方法。 請參閱下面的工作示例:

import handler from 'src/pages/api/index';
import { createOne } from 'src/lib/database';

jest.mock('src/lib/database', () => ({
  __esModule: true,
  createOne: jest.fn().mockImplementation(async (val) => 1)
}));

test('it calls the mock and returns id: 1', async () => {
  const { req, res } = mockReqRes();  // using node-mocks-http, out of scope
  await handler(req, res);
  expect(createOne.mock.calls.length).toEqual(1);
  expect(res._getJSONData()).toEqual(
    expect.objectContaining({
      id: 1
    })
  );
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM