调用了响应.重定向的JestAssert

2ic8powd  于 2024-01-04  发布在  Jest
关注(0)|答案(2)|浏览(150)

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

  1. async function MyController(req, res, next){
  2. if (condition1) {
  3. // render logic
  4. }
  5. if (condition2) {
  6. res.redirect(SOME_CONSTANT);
  7. }
  8. }

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

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


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

von4xj4u

von4xj4u1#

查看它被调用的次数:

  1. const myController = require('../my-controller')
  2. describe('my-controller', () => {
  3. let res
  4. beforeEach(() => {
  5. res = {
  6. redirect: jest.fn(),
  7. }
  8. })
  9. test('should call res.redirect', async () => {
  10. await myController({}, res)
  11. expect(res.redirect.mock.calls.length).toEqual(1)
  12. })
  13. })

字符串

展开查看全部
fcy6dtqo

fcy6dtqo2#

  1. const myController = require('../my-controller');
  2. describe('my-controller', () => {
  3. let res;
  4. beforeEach(() => {
  5. res = {
  6. redirect: jest.fn(),
  7. };
  8. });
  9. test('should call res.redirect with the correct arguments', async () => {
  10. // Arrange
  11. const expectedRedirectUrl = '/some/path';
  12. // Act
  13. await myController({}, res, expectedRedirectUrl);
  14. // Assert
  15. expect(res.redirect).toHaveBeenCalledTimes(1);
  16. expect(res.redirect).toHaveBeenCalledWith(expectedRedirectUrl);
  17. });
  18. });

字符串

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

展开查看全部

相关问题