Skip to content

Commit

Permalink
feat(testes): update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
lariane-guerra committed Feb 20, 2025
1 parent 6c927f3 commit f8ffbc6
Show file tree
Hide file tree
Showing 14 changed files with 202 additions and 298 deletions.
14 changes: 7 additions & 7 deletions src/iframes/listener.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { validation } from 'src/events'
import { listener } from './listener'
import { CSSClasses, Event } from 'src/enums'
import { eventsEmitter } from 'src/tokenization'
import { createEventMock } from 'tests/mocks/common-configurations'
import { handleCreateMockEvent } from 'tests/mocks'

vi.mock('src/events', async () => {
const actual = await vi.importActual('src/events')
Expand Down Expand Up @@ -55,7 +55,7 @@ describe('listener', () => {
listener()
const messageHandler = addEventListenerSpy.mock.calls[0][1]

const event = createEventMock('successOrigin')
const event = handleCreateMockEvent('successOrigin')
messageHandler(event)

expect(document.querySelector).toHaveBeenCalledWith(
Expand All @@ -68,7 +68,7 @@ describe('listener', () => {
listener()
const messageHandler = addEventListenerSpy.mock.calls[0][1]

const event = createEventMock('test', 'https://wrong-origin.com')
const event = handleCreateMockEvent('test', 'https://wrong-origin.com')

messageHandler(event)
expect(document.querySelector).not.toHaveBeenCalled()
Expand All @@ -78,7 +78,7 @@ describe('listener', () => {
listener()
const messageHandler = addEventListenerSpy.mock.calls[0][1]

const event = createEventMock(Event.Validity)
const event = handleCreateMockEvent(Event.Validity)

messageHandler(event)
expect(validation).toHaveBeenCalledWith(
Expand All @@ -90,7 +90,7 @@ describe('listener', () => {
test('should emit CardTypeChanged event for CardTypeChanged event type', () => {
listener()
const messageHandler = addEventListenerSpy.mock.calls[0][1]
const event = createEventMock(Event.CardTypeChanged)
const event = handleCreateMockEvent(Event.CardTypeChanged)

const updateEvent = {
...event,
Expand All @@ -115,7 +115,7 @@ describe('listener', () => {
listener()
const messageHandler = addEventListenerSpy.mock.calls[0][1]

const event = createEventMock(Event.Focus)
const event = handleCreateMockEvent(Event.Focus)

messageHandler(event)
expect(eventsEmitter.emit).toHaveBeenCalledWith('focus', {
Expand All @@ -132,7 +132,7 @@ describe('listener', () => {
listener()
const messageHandler = addEventListenerSpy.mock.calls[0][1]

const event = createEventMock(Event.Blur)
const event = handleCreateMockEvent(Event.Blur)

messageHandler(event)
expect(eventsEmitter.emit).toHaveBeenCalledWith('blur', {
Expand Down
6 changes: 4 additions & 2 deletions src/iframes/loaded.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { URL_HOSTED_FIELD } from 'src/constants'
import { loaded } from './loaded'
import { camelToKebabCase } from 'src/utils'
import { configurations } from '../../tests/mocks/common-configurations'
import { configurationsSDK } from 'tests/mocks'

vi.mock('./create', () => ({
create: vi.fn((field) => {
Expand All @@ -16,8 +16,10 @@ vi.mock('./create', () => ({

describe('loaded', () => {
test('should be possible to loaded the iframes', () => {
loaded(configurations.options?.config)
loaded(configurationsSDK.options?.config)

const iframes = document.querySelectorAll('iframe')

expect(iframes).toHaveLength(4)

iframes.forEach((iframe) => {
Expand Down
41 changes: 14 additions & 27 deletions src/iframes/submit.test.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,40 @@
import { submit } from './submit'
import { configurations } from 'tests/mocks/common-configurations'
import {
configurationsSDK,
configurationWithSubmitData,
handleRemoveIframe,
handleSetupIframeInDOM,
} from 'tests/mocks'

describe('submit', () => {
let iframeCardNumber: HTMLIFrameElement

beforeAll(() => {
iframeCardNumber = document.createElement('iframe')
iframeCardNumber.name = 'card-number'
document.body.appendChild(iframeCardNumber)

Object.defineProperty(iframeCardNumber, 'contentWindow', {
value: {
postMessage: vi.fn(),
},
writable: true,
iframeCardNumber = handleSetupIframeInDOM('card-number', {
postMessage: vi.fn(),
})
})

afterEach(() => {
vi.clearAllMocks()

if (document.body.contains(iframeCardNumber)) {
document.body.removeChild(iframeCardNumber)
}
handleRemoveIframe(iframeCardNumber)
})

test('should send a post message with authorization data', () => {
submit(configurations)
submit(configurationsSDK)

expect(iframeCardNumber).toBeInTheDocument()
expect(iframeCardNumber.contentWindow?.postMessage).toHaveBeenCalledTimes(1)
expect(iframeCardNumber.contentWindow?.postMessage).toHaveBeenCalledWith(
{
type: 'submit',
data: {
authorizationData: {
clientId: 'test-client-id',
apiKey: 'test-api-key',
},
sandbox: true,
},
},
configurationWithSubmitData,
'*',
)
})

test('should not send a post message if iframe does not exist', () => {
iframeCardNumber.remove()
handleRemoveIframe(iframeCardNumber)

submit(configurations)
submit(configurationsSDK)
expect(iframeCardNumber.contentWindow?.postMessage).not.toHaveBeenCalled()
})
})
11 changes: 1 addition & 10 deletions src/iframes/submit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,7 @@ export function submit(configurations: MalgaConfigurations) {
iframeCardNumber.contentWindow!,
'*',
)
console.log('Sending message:', {
type: 'submit',
data: {
authorizationData: {
clientId: configurations.clientId,
apiKey: configurations.apiKey,
},
sandbox: configurations.options?.sandbox,
},
})

iframePostMessage.send(Event.Submit, {
authorizationData: {
clientId: configurations.clientId,
Expand Down
220 changes: 104 additions & 116 deletions src/tokenize/tokenize.test.ts
Original file line number Diff line number Diff line change
@@ -1,116 +1,104 @@
// import {
// formElementsMock,
// handleFormMock,
// malgaConfigurations,
// } from 'tests/mocks/common-configurations'
// import { generateForm } from 'tests/mocks/form-dom'
// import { Malga } from 'src/common/malga'
// import { Tokenize } from './tokenize'

// vi.mock('src/common/malga', async (importOriginal) => {
// const Malga = await importOriginal<typeof import('src/common/malga')>()
// return {
// ...Malga,
// tokenization: vi.fn(),
// }
// })

// describe('Tokenize', () => {
// describe('handle', () => {
// beforeEach(() => {
// document.body.innerHTML = ''
// })

// test('should be possible for a tokenId to exist when elements are passed correctly', async () => {
// generateForm()

// const malga = new Malga(malgaConfigurations(false))

// const tokenizeObject = new Tokenize(malga, formElementsMock)
// const tokenId = await tokenizeObject.handle()

// expect(tokenId).toBeTruthy()
// })
// test('should be possible to return a tokenId equal to sandbox-token-id when configurations include sandbox equal to true', async () => {
// generateForm()

// const malga = new Malga(malgaConfigurations(true))

// const tokenizeObject = new Tokenize(malga, formElementsMock)

// const tokenId = await tokenizeObject.handle()
// expect(tokenId).toMatchObject({ tokenId: 'sandbox-token-id' })
// })
// test('should be possible to return a tokenId equal to sandbox-token-id when configurations include production equal to true', async () => {
// generateForm()

// const malga = new Malga(malgaConfigurations(false))

// const tokenizeObject = new Tokenize(malga, formElementsMock)

// const tokenId = await tokenizeObject.handle()
// expect(tokenId).toMatchObject({ tokenId: 'production-token-id' })
// })
// test('should be possible to return error when elements are not passed correctly', async () => {
// generateForm()

// const malga = new Malga(malgaConfigurations(false))

// const elementsMock = {
// form: 'jenjen',
// holderName: 'le',
// number: 'li',
// expirationDate: 'lo',
// cvv: 'lu',
// }
// const tokenizeObject = new Tokenize(malga, elementsMock)

// await expect(tokenizeObject.handle()).rejects.toThrowError(
// "Cannot read properties of null (reading 'value')",
// )
// })
// test('should be possible to return an error if the apiKey and clientId settings are empty', async () => {
// generateForm()

// const malgaConfigurationsEmpty = {
// apiKey: '',
// clientId: '',
// }

// const malga = new Malga(malgaConfigurationsEmpty)

// const tokenizeObject = new Tokenize(malga, formElementsMock)

// await expect(tokenizeObject.handle).rejects.toThrowError(
// "Cannot read properties of undefined (reading 'elements')",
// )
// })
// test('should be possible to return an error if the form inputs do not have values assigned', async () => {
// const {
// form,
// holderNameInput,
// cvvInput,
// expirationDateInput,
// numberInput,
// } = handleFormMock()

// form.setAttribute(formElementsMock.form, '')
// holderNameInput.setAttribute(formElementsMock.holderName, '')
// numberInput.setAttribute(formElementsMock.number, '')
// cvvInput.setAttribute(formElementsMock.cvv, '')
// expirationDateInput.setAttribute(formElementsMock.expirationDate, '')

// document.body.appendChild(form)
// form.appendChild(holderNameInput)
// form.appendChild(numberInput)
// form.appendChild(expirationDateInput)
// form.appendChild(cvvInput)

// const malga = new Malga(malgaConfigurations(false))

// const tokenizeObject = new Tokenize(malga, formElementsMock)

// await expect(tokenizeObject.handle()).rejects.toThrowError()
// })
// })
// })
import { Event } from 'src/enums'
import { submit } from 'src/iframes'
import { Tokenize } from './../tokenize/tokenize'
import * as iframesModule from 'src/iframes'
import {
handleSetupIframeInDOM,
handleRemoveIframe,
handleCreateMessageEventMock,
configurationsSDK,
} from 'tests/mocks'

describe('tokenize', () => {
let iframe: HTMLIFrameElement
let contentWindowMock: Window

beforeEach(() => {
contentWindowMock = {
postMessage: vi.fn(),
addEventListener: vi.fn(),
} as unknown as Window

iframe = handleSetupIframeInDOM('card-number', contentWindowMock)
})

afterEach(() => {
vi.clearAllMocks()
handleRemoveIframe(iframe)
})

test('should resolve with token data on successful message', async () => {
const tokenize = new Tokenize(configurationsSDK)
const promise = tokenize.handle()
const messageEvent = handleCreateMessageEventMock(
Event.Tokenize,
'623e25e1-9c40-442e-beaa-a9d7b735bdc1',
)
global.dispatchEvent(messageEvent)

const response = await promise
expect(response).toEqual('623e25e1-9c40-442e-beaa-a9d7b735bdc1')
expect(contentWindowMock.postMessage).toHaveBeenCalledTimes(1)
})

test('should handle errors during message processing', async () => {
const tokenize = new Tokenize(configurationsSDK)

const promise = tokenize.handle()

const messageEvent = handleCreateMessageEventMock(
Event.Tokenize,
undefined,
'https://develop.d3krxmg1839vaa.amplifyapp.com',
)
global.dispatchEvent(messageEvent)

const response = await promise
expect(response).toEqual(undefined)
expect(contentWindowMock.postMessage).toHaveBeenCalledTimes(1)
})

test('should ignore messages from unauthorized origins', async () => {
const tokenize = new Tokenize(configurationsSDK)
const consoleErrorSpy = vi
.spyOn(console, 'error')
.mockImplementation(() => {})
const promise = tokenize.handle()

const messageEvent = handleCreateMessageEventMock(
Event.Tokenize,
'623e25e1-9c40-442e-beaa-a9d7b735bdc1',
'https://unauthorized.com',
)
global.dispatchEvent(messageEvent)

await new Promise((resolve) => setTimeout(resolve, 10))

expect(consoleErrorSpy).toHaveBeenCalledWith('Unauthorized')
expect(promise).not.resolves
expect(contentWindowMock.postMessage).toHaveBeenCalledTimes(1)
consoleErrorSpy.mockRestore()
})

test('should call submit with correct configurations', () => {
const submitSpy = vi.spyOn(iframesModule, 'submit')
new Tokenize(configurationsSDK).handle()
expect(submitSpy).toHaveBeenCalledWith(configurationsSDK)
submitSpy.mockRestore()
})

test('should handle iframe not found', () => {
const querySelectorSpy = vi.spyOn(document, 'querySelector')
querySelectorSpy.mockReturnValue(null)

const consoleErrorSpy = vi.spyOn(console, 'error')
submit(configurationsSDK)

expect(consoleErrorSpy).toHaveBeenCalledWith(
'iframeCardNumber is null or has no contentWindow, cannot send postMessage',
)

querySelectorSpy.mockRestore()
consoleErrorSpy.mockRestore()
})
})
Empty file removed tests/iframes.ts
Empty file.
Loading

0 comments on commit f8ffbc6

Please sign in to comment.