【发布时间】:2018-06-21 10:58:22
【问题描述】:
我一直很难找到关于如何使用 jest.fn() 模拟 typescript 类和类上的方法的好资源(例如 express'Request、Response 和 NextFunction,以及 @987654325 @ 猫鼬模型上的方法。)
例如,假设我有以下模型和控制器:
模型/Foo.ts:
import * as mongoose from "mongoose"
export type FooModel = mongoose.Document & {
owner: mongoose.Schema.Types.ObjectId,
bars: string[]
}
const fooSchema = new mongoose.Schema({
owner: { type: mongoose.Schema.Types.ObjectId, ref: "User", index: true },
bars: [String]
}
export const Foo = mongoose.model<FooModel>("Foo", fooSchema)
控制器/foo.ts:
import { Request, Response, NextFunction } from "express";
import { Foo, FooModel } from "../models/Foo";
export let createFoo = async (req: Request, res: Response, next: NextFunction) => {
try {
const foo = new Foo({
owner: req.user._id,
bars: req.body.bars
});
await foo.save();
res.status(200).json(foo);
} catch (err) {
next(err)
}
}
我想添加一些单元测试:
import { Request, Response, NextFunction } from "express";
import { Foo } from "../../src/models/Foo";
import * as fooController from "../../src/controllers/foo";
import {} from "jest";
describe("createFoo", async () => {
let req: Request;
let res: Response;
let next: NextFunction;
const bars = ["baz", "qux", "quux"];
beforeEach(() => {
// Mock req, res and next
// Set req.body.bars equal to bars
// Stub out Foo.save() so that we don't actually save to the db
});
it("should add bars to the foo", async () => {
await fooController.createFoo(req, res, next);
responseData = JSON.parse(res.json)
expect(responseData.bars).toEqual(bars);
});
it("should save the foo", async () => {
await fooController.createFoo(req, res, next);
expect(Foo.prototype.save).toHaveBeenCalled();
}
it("should call next on error", async () => {
const err = new Error();
// Set up Foo.save() to throw err
await fooController.createFoo(req, res, next);
expect(next).toHaveBeenCalledWith(err);
}
});
我遇到的主要问题是注释掉的部分:我还没有弄清楚如何实际模拟 req、res 和 next,或者如何删除 Foo.save() 或制作它抛出一个错误。我怎样才能做到这一点?
【问题讨论】:
-
您找到解决方案了吗?
-
凯蒂有什么解决办法吗?
标签: typescript express mongoose jestjs