灏天阁

Node/Koa2[50]: 创建微博-单元测试

· Yin灏

单元测试

test/blog/model.test.js

let BLOG_ID = "";
const { Blog } = require("../../src/db/model/index");

test("微博数据模型各个属性,符合预期", () => {
  const blog = Blog.build({
    userId: 1,
    content: "微博内容",
    image: "/test.png",
  });
  expect(blog.userId).toBe(1);
  expect(blog.content).toBe("微博内容");
  expect(blog.image).toBe("/test.png");
});

home 测试

test/blog/home.test.js

const server = require("../server");
const { COOKIE } = require("../testUserInfo");

test("创建一条微博,应该成功", async () => {
  const content = "单元测试自动创建的微博_" + Date.now();
  const image = "/xxx.png";
  const res = await server
    .post("/api/blog/create")
    .send({
      content,
      image,
    })
    .set("cookie", COOKIE);
  expect(res.body.errno).toBe(0);
  expect(res.body.data.content).toBe(content);
  expect(res.body.data.image).toBe(image);
  // 微博 id
  BLOG_ID = res.body.data.id;
});

test/testUserInfo.js

module.exports = {
  const COOKIE = "从页面接口中获取 cookie";
}

- Book Lists -