这是我的路线之一。
const actor = await Actor.findById(req.params.id);
if(!actor) throw new Error("Actor not found");
res.render('admin/actors/edit_actor',{actor:actor});
问题是我不知道如何测试是否由于渲染功能而返回了有效的actor。
================================================ =================
如果我写以下内容
const actor = await Actor.findById(req.params.id);
if(!actor) throw new Error("Actor not found");
res.send({actor:actor});
我知道该如何测试,因为这个角色会在身体参数中。例如:
//测试
const res = await request(server).get('/actor/2');
res.body与演员相同
那么问题:
1)我如何测试呈现某些视图的第一个示例?
2)测试的第一个示例需要进行集成测试。对于第二个示例,我们应该编写功能测试。我说的对吗?
答案 0 :(得分:0)
在单元测试中,您应该模拟依赖关系,因此,如果要测试控制器,则应该模拟req
和res
对象以及模型。例如
import Actor from '../model/Actor';
const controller = (req, res) => {
const actor = await Actor.findById(req.params.id);
if(!actor) throw new Error("Actor not found");
res.render('admin/actors/edit_actor',{actor:actor});
}
import Actor from '../model/Actor';
jest.mock('../model/Actor');
describe('controller', () => {
const req = {
params: { id: 101 }
};
const res. = {
render: jest.fn()
};
beforeAll(() => {
Actor.findById.mockClear();
controller(req, res);
});
describe('returning an actor', () => {
beforeAll(() => {
res.render.mockClear();
Actor.findById.mockResolvedValue({
name: "Some Actor"
});
controller(req, res);
});
it('should get actor by id', () => {
expect(Actor.findById).toHaveBeenCalledWith(101);
});
it('should call res.render', () => {
expect(res.render).toHaveBeenCalledWith('admin/actors/edit_actor', { actor });
})
});
describe('not returning an actor', () => {
beforeAll(() => {
res.render.mockClear();
Actor.findById.mockResolvedValue(undefined);
controller(req, res);
});
it('should throw an Error', () => {
expect(() => controller(req, res)).toThrow(Error);
});
it('should not call res.render', () => {
expect(res.render).not.toHaveBeenCalled();
});
});
});