@vettvangur/testing
v0.0.28
Published
Testing.
Maintainers
Keywords
Readme
vettvangur-testing
Testing.
We test the most critical parts of out applications. That means:
- Fetches
- Uptime
- etc.
Example
This example is from the recaptcha test.
// recaptcha.test.ts
import recaptcha from './recaptcha'
describe('recaptcha module', () => {
// Override the global grecaptcha for our tests
beforeEach(() => {
global.grecaptcha = {
getResponse: jest.fn(),
}
})
describe('validate', () => {
it('should return false when grecaptcha.getResponse returns an empty string', () => {
;(global.grecaptcha.getResponse as jest.Mock).mockReturnValue('')
expect(recaptcha.validate()).toBe(false)
})
it('should return true when grecaptcha.getResponse returns a non-empty string', () => {
;(global.grecaptcha.getResponse as jest.Mock).mockReturnValue('non-empty')
expect(recaptcha.validate()).toBe(true)
})
})
describe('handleError', () => {
let event: Event
let preventDefaultSpy: jest.Mock
let element: HTMLElement
beforeEach(() => {
// Create a dummy event and spy on preventDefault
event = new Event('dummy', { bubbles: true, cancelable: true })
preventDefaultSpy = jest.fn()
event.preventDefault = preventDefaultSpy
// Create a dummy element without any classes
element = document.createElement('div')
element.className = ''
})
it('should call event.preventDefault and remove "hide" class when validate returns false', () => {
// Set grecaptcha.getResponse to return empty, so validate() is false.
;(global.grecaptcha.getResponse as jest.Mock).mockReturnValue('')
// Initially, element does not have "hide"
expect(element.classList.contains('hide')).toBe(false)
recaptcha.handleError(event, element)
// The handler should first add "hide", then remove it because validate() is false.
expect(preventDefaultSpy).toHaveBeenCalled()
expect(element.classList.contains('hide')).toBe(false)
})
it('should add "hide" class and not call preventDefault when validate returns true', () => {
// Set grecaptcha.getResponse to return non-empty, so validate() is true.
;(global.grecaptcha.getResponse as jest.Mock).mockReturnValue('non-empty')
expect(element.classList.contains('hide')).toBe(false)
recaptcha.handleError(event, element)
// Since validate() is true, the "hide" class remains and preventDefault is not called.
expect(preventDefaultSpy).not.toHaveBeenCalled()
expect(element.classList.contains('hide')).toBe(true)
})
it('should not throw if element is null', () => {
// Even if element is null, handleError should exit without error.
expect(() => recaptcha.handleError(event, null as unknown as HTMLElement)).not.toThrow()
})
})
})
