简体   繁体   English

如何测试使用middy时调用的处理程序function

[英]how to test that handler function is called when using middy

im using an http request function as the handler function in middy and then use the ssm middleware to fetch some ssm parameters before initiating the http request. im using an http request function as the handler function in middy and then use the ssm middleware to fetch some ssm parameters before initiating the http request. like this:像这样:

  const makeThirdPartyServiceRequest = middy(async ({ params }) => {
  logger.info(`SENDING Request to ${endpoint} API`)
  const url = `https://someurltoathirdpartyservice`
  const options = {
    method: 'POST',
    body: params
  }

  return helpers.makeRequest(url, options)
})
makeThirdPartyServiceRequest.use(ssm(......))

However in my jest unit test Im trying to mock makeThirdPartyServiceRequest and explicitly say it should resolve to a value:然而,在我开玩笑的单元测试中,我试图模拟 makeThirdPartyServiceRequest 并明确表示它应该解析为一个值:

jest.mock('../src/thirdPartyService', () => ({
  __esModule: true,
  default: {
    ...(jest.requireActual('../src/thirdPartyService') as { default: {} }).default,
    makeThirdPartyServiceRequest: jest.fn()
  }
}))
export {}
import thirdPartyService from '../src/thirdPartyService'

And then in the test i say:然后在测试中我说:

describe('makeThirdPartyServiceRequest()', () => {
  it('should makeThirdPartyServiceRequest', async () => {
    // Given

    // })
    const mockedThirdPartyServiceRequest = mocked(thirdPartyService.makeThirdPartyServiceRequest).mockResolvedValue({})
    // When
    const result = await thirdPartyService.makeThirdPartyServiceRequest(something)
    // Then
    expect(mockedThirdPartyServiceRequest).toHaveBeenCalledTimes(1)
    expect(mockedThirdPartyServiceRequest.mock.calls[0][0].params.toString()).toBe(expectedParams)
  })
})

However for some reason the middy middleware is still being invoked, which i clearly dont want and i have tried to mock away... what am i doing wrong?但是由于某种原因,仍然在调用 middy 中间件,这显然是我不想要的,我试图嘲笑......我做错了什么?

hoangdv answer is also valid, but i will answer as well how i continued. hoangdv 的回答也是有效的,但我也会继续回答。

if you completely want to mock middy you mock like following:如果你完全想模拟 middy,你可以模拟如下:

    jest.mock('@middy/core', () => {
      return (handler) => {
        return {
          use: jest.fn().mockImplementation(() => {
            // ...use(ssm()) will return handler function
            return {
              before: jest.fn().mockReturnValue(handler)
            }
          })
        }
      }
    })

However if you dont want to completely mock middy, you can instead mock the async getInternal function from middy/util called in before like this:但是,如果您不想完全模拟 middy,则可以改为模拟之前调用的 middy/util 中的异步 getInternal function,如下所示:

    jest.doMock('@middy/util', () => ({
      ...(jest.requireActual('@middy/util') as {}),
      getInternal: jest.fn()
    }))
import { getInternal } from '@middy/util'

and then in the test然后在测试中

    describe('thirdPartyService()', () => {
      beforeEach(() => {
        jest.spyOn(helpers, 'makeRequest') // spy on helpers unit
      })
    
      describe('makeThirdPartyServiceRequest', () => {
        it('should make a request with correct parameters', async () => {
          // Given
          const url = `https://someurltoathirdpartyservice`
          const params = 'any params'
          const apiResponse = 'any response'
          mocked(getInternal).mockResolvedValue({
          twilioSecrets: { accountSid: 'someSID', serviceId: 
          'someServiceID', token: 'someToken' }
          })
          mocked(helpers.makeRequest).mockResolvedValue(apiResponse)
    
          // When
          const actual = await thirdPartyService.makeThirdPartyServiceRequest(params)
    
          // Then
          expect(actual).toBe(apiResponse)
          expect(helpers.makeRequest).toHaveBeenCalledWith(
            url,
            {
              method: 'POST',
              body: params
            }
          )
        })
      })
    })

this will mock the async part of middy.这将模拟 middy 的异步部分。

You need to mock middy instead, to make it becomes a useless function.您需要改为模拟middy ,使其成为无用的 function。 That function recipe a function as a parameter and return that parameter. function 配方将 function 作为参数并返回该参数。

import thirdPartyService from '../src/thirdPartyService'

jest.mock('@middy/core', () => {
  return (handler) => {
    return {
      use: jest.fn().mockReturnValue(handler), // ...use(ssm()) will return handler function
    }
  }
})

describe('thirdPartyService()', () => {
  beforeEach(() => {
    jest.spyOn(helpers, 'makeRequest') // spy on helpers unit
  })

  describe('makeThirdPartyServiceRequest', () => {
    it('should make a request with correct parameters', async () => {
      // Given
      const url = `https://someurltoathirdpartyservice`
      const params = 'any params'
      const apiResponse = 'any response'
      mocked(helpers.makeRequest).mockResolvedValue(apiResponse)

      // When
      const actual = await thirdPartyService.makeThirdPartyServiceRequest(params)

      // Then
      expect(actual).toBe(apiResponse)
      expect(helpers.makeRequest).toHaveBeenCalledWith(
        url,
        {
          method: 'POST',
          body: params
        }
      )
    })
  })
})

暂无
暂无

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

相关问题 如何测试使用CO调用的生成器功能 - How to test a generator function called using CO 如何测试单击按钮时是否调用了 function(茉莉花) - How to test if a function is called when a button is clicked(jasmine) 如何测试componentDidMount时调用的组件function? - How to test a component function being called when componentDidMount? 如何使用 Cypress 对在 React 组件上调用的回调函数进行单元测试 - How to unit test a callback function was called on a React component using Cypress 如何测试是否在异步调用的测试函数B中调用了函数A - How to test if function A was called inside the test function B if it was called asynchronously 如何获取匿名函数以保持它在事件处理程序中调用时最初的作用域 - How to get an anonymous function to keep the scoping it had originally when called in an event handler 使用 sinon 在包装器中调用对象时如何进行单元测试? - How to unit test when object is called within a wrapper using sinon? 当使用 React 测试库更改数据属性时,如何编写一个测试用例来验证 function 是否被正确调用? - How can I write a test case that verifies that the function is being called correctly when the data prop changes using React Testing Library? 启动时调用函数时单元测试失败 - Unit test failing when function called on startup 在if语句中调用函数时的茉莉花测试用例 - Jasmine test case when a function is called in an if statement
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM