调用了响应.重定向的JestAssert

2ic8powd  于 9个月前  发布在  Jest
关注(0)|答案(2)|浏览(98)

我正在使用jest测试一个路由控制器。

async function MyController(req, res, next){
     if (condition1) {
        // render logic
     }
     if (condition2) {
        res.redirect(SOME_CONSTANT);
     }
}

字符串
我如何Assertresponse.redirect已被调用?

const req = { query: {} };
const res = { redirect: jest.fn() };
expect(res.redirect).toHaveBeenCalled();


但这显然是行不通的,除非我真的可以用jest.mock()模拟reponse

von4xj4u

von4xj4u1#

查看它被调用的次数:

const myController = require('../my-controller')

describe('my-controller', () => {
  let res

  beforeEach(() => {
    res = {
      redirect: jest.fn(),
    }
  })

  test('should call res.redirect', async () => {
    await myController({}, res)
    expect(res.redirect.mock.calls.length).toEqual(1)
  })
})

字符串

fcy6dtqo

fcy6dtqo2#

const myController = require('../my-controller');

describe('my-controller', () => {
  let res;

  beforeEach(() => {
    res = {
      redirect: jest.fn(),
    };
  });

  test('should call res.redirect with the correct arguments', async () => {
    // Arrange
    const expectedRedirectUrl = '/some/path';

    // Act
    await myController({}, res, expectedRedirectUrl);

    // Assert
    expect(res.redirect).toHaveBeenCalledTimes(1);
    expect(res.redirect).toHaveBeenCalledWith(expectedRedirectUrl);
  });
});

字符串

这应该更好地工作,并有更好的覆盖面

相关问题