Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I test node.js template render in jest

This is one of my routes.

const actor = await Actor.findById(req.params.id);
if(!actor) throw new Error("Actor not found");
res.render('admin/actors/edit_actor',{actor:actor});

The thing is I don't know how to test if valid actor gets returned because of render function.

================================================================

If I write the following

const actor = await Actor.findById(req.params.id);
    if(!actor) throw new Error("Actor not found");
    res.send({actor:actor});

I know how to test this because this actor would be in body parameters. such as:

//test

const res = await request(server).get('/actor/2');

res.body is the same as actor

So questions:

1) how do I test the first example which renders some view?

2) first example to test there's an integration test needed. and for the second example, we should write functional test. Am I right?

like image 416
Nika Kurashvili Avatar asked Jun 25 '26 10:06

Nika Kurashvili


1 Answers

In an unit test you're supposed to mock your dependencies, so if you're testing your controller you should mock the req and res objects as well as the model. For example

Implementation

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});
}

Unit Test

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();
    });
  });
});
like image 114
Teneff Avatar answered Jun 27 '26 05:06

Teneff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!