繁体   English   中英

Jest 无法检测到模拟 function 调用

[英]Jest is unable to detect the mock function call

我正在 Express 应用程序的 controller 上编写单元测试。 我是 mocking res.send方法,并希望在用户传递这样的有效数据时调用它:

describe('>> CONTROLLERS -- Exercise -- deleteExercise', () => {
  let res

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

  it('sends error as response if id was not passed', () => {
    const req = {
      body : {}
    }
    deleteExercise(req, res)

    expect(res.send).toHaveBeenCalledWith({
      error : 'please pass id field to delete the exercise.'
    })
  })

  it('calls the deleteExercise class method if the id was passed', () => {
    const req = {
      body : {
        id : 1234
      }
    }

    deleteExercise(req, res)

    expect(Exercise.deleteExercise).toHaveBeenCalledWith(1234)
    expect(res.send).toHaveBeenCalled()
    // expect(res.send).toHaveBeenCalledWith(mockData)
  })
})

第一个测试运行良好,但第二个不是。 我已经添加了控制台来检查res.send是否被调用,在代码中它被调用,但是 Jest 对expect(res.send).toHaveBeenCalled()测试失败。 你能帮我解决我在这里缺少的东西吗......

在花了一些时间进行调试之后,我认为您还需要为您的模拟响应提供状态。

mockResponse = {
   send : jest.fn()
   status: jest.fn(() => mockResponse),
}
describe('>> CONTROLLERS -- Exercise -- deleteExercise', () => {
  let mockResponse

  beforeEach(() => {
    mockResponse = {
      send : jest.fn()
      status: jest.fn(() => mockResponse),
    }
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('sends error as response if id was not passed', () => {
    const mockRequest = {
      body : {}
    }
    deleteExercise(mockRequest, mockResponse)

    expect(mockResponse.send).toHaveBeenCalledWith({
      error : 'please pass id field to delete the exercise.'
    })
  })


  it('calls the deleteExercise class method if the id was passed', () => {
    const mockRequest = {
      body : {
        id : 1234
      }
    }

   deleteExercise(mockRequest, mockResponse)
 // deleteExercise is called with req, res arguments

    expect(Exercise.deleteExercise).toHaveBeenCalled()
    expect(Exercise.deleteExercise).toHaveBeenCalledWith(mockRequest, mockResponse) 
    expect(Exercise.deleteExercise).toHaveBeenCalledTimes(1)
    expect(mockResponse.send).toHaveBeenCalled()
    expect(mockResponse.send).toHaveBeenCalledWith(1234)
    expect(mockResponse.send).toHaveBeenCalledTimes(1)

  })
})

deleteExercise function 是用resreq调用的,而不是用id调用的。 首先检查是否调用了 deleteExercise,然后检查是否调用了与 arguments 相同的 function。 然后稍后检查 function 被调用了多少次。

还有一件事,在每个测试用例之后清除所有模拟。

afterEach(() => {
    jest.clearAllMocks();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM