Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

109
Visualizações
cómo hacer una prueba unitaria si se llama a la función del controlador cuando se usa middy

estoy usando una función de solicitud http como función de controlador en medio y luego uso el middleware ssm para obtener algunos parámetros ssm antes de iniciar la solicitud http. como esto:

 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(......))

Sin embargo, en mi prueba de unidad de broma, estoy tratando de burlarme de makeThirdPartyServiceRequest y decir explícitamente que debería resolverse en un valor:

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

Y luego en la prueba digo:

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

Sin embargo, por alguna razón, el middleware middy todavía se está invocando, lo que claramente no quiero y he tratado de burlarme... ¿qué estoy haciendo mal?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

En su lugar, debe burlarse de middy , para que se convierta en una función inútil. Esa función receta una función como parámetro y devuelve ese parámetro.

 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 } ) }) }) })
about 4 years ago · Juan Pablo Isaza Relatório

0

La respuesta de hoangdv también es válida, pero también responderé cómo continué.

si quieres burlarte por completo de Middy, te burlas de la siguiente manera:

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

Sin embargo, si no desea burlarse por completo de middy, puede burlarse de la función asíncrona getInternal de middy/util llamada antes de esta manera:

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

y luego en la prueba

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

esto se burlará de la parte asíncrona de middy.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda