【问题标题】:how to mock db response in jest?如何开玩笑地模拟数据库响应?
【发布时间】:2021-11-24 20:54:28
【问题描述】:

我想模拟来自 API 请求的数据库响应。我正在尝试应用手动模拟,但它不起作用。每次都从数据库响应,而不是从模拟。我该如何解决?这是我的代码:

app.test.ts

jest.mock('../services/__mocks__/image');

describe("It shuld be get methoad", () => {
  it("get all image url", async () => {
    const res = await request(app).get("/api/v1/all");
    expect(res.statusCode).toBe(200);
    // console.log(res.body);
    let images = res.body
    // expect(images.length).toBeGreaterThan(0);
    expect(images.length).toBe(1);
  });
});

services/mocks/image.ts

let images = [
  {
    "_id": "61364c4552781af510baf4bf",
    "title": "9-06_09_2021_11_13_41",
    "imageURL": "upload/9-06_09_2021_11_13_41.jpeg",
    "imageFullURL": "http://localhost:4000/9-06_09_2021_11_13_41.jpeg",
    "createdAt": "2021-09-06T17:13:41.390Z"
  }
];

export const allImages = () => {
  console.log("mock used");
  return images;
};

服务/image.ts

import Image from "../models/image";

export const allImages = async () => {
    console.log("main used");
    const all = await Image.find();
    return all;
}

【问题讨论】:

    标签: node.js express jestjs supertest


    【解决方案1】:

    我没有模拟,而是使用mongodb-memory-server 包获得了解决方案。

    【讨论】:

      猜你喜欢
      • 2020-11-18
      • 1970-01-01
      • 2017-07-01
      • 1970-01-01
      • 2020-08-20
      • 2021-05-27
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多