|
| 1 | +import React from 'react' |
| 2 | +import {render, fireEvent, cleanup} from 'react-testing-library' |
| 3 | + |
| 4 | +class CostInput extends React.Component { |
| 5 | + state = { |
| 6 | + value: '', |
| 7 | + } |
| 8 | + |
| 9 | + removeDollarSign = value => (value[0] === '$' ? value.slice(1) : value) |
| 10 | + getReturnValue = value => (value === '' ? '' : `$${value}`) |
| 11 | + handleChange = ev => { |
| 12 | + ev.preventDefault() |
| 13 | + const inputtedValue = ev.currentTarget.value |
| 14 | + const noDollarSign = this.removeDollarSign(inputtedValue) |
| 15 | + if (isNaN(noDollarSign)) return |
| 16 | + this.setState({value: this.getReturnValue(noDollarSign)}) |
| 17 | + } |
| 18 | + |
| 19 | + render() { |
| 20 | + return ( |
| 21 | + <input |
| 22 | + value={this.state.value} |
| 23 | + aria-label="cost-input" |
| 24 | + onChange={this.handleChange} |
| 25 | + /> |
| 26 | + ) |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +const setup = () => { |
| 31 | + const utils = render(<CostInput />) |
| 32 | + const input = utils.getByLabelText('cost-input') |
| 33 | + return { |
| 34 | + input, |
| 35 | + ...utils, |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +afterEach(cleanup) |
| 40 | + |
| 41 | +test('It should keep a $ in front of the input', () => { |
| 42 | + const {input} = setup() |
| 43 | + fireEvent.change(input, {target: {value: '23'}}) |
| 44 | + expect(input.value).toBe('$23') |
| 45 | +}) |
| 46 | +test('It should allow a $ to be in the input when the value is changed', () => { |
| 47 | + const {input} = setup() |
| 48 | + fireEvent.change(input, {target: {value: '$23.0'}}) |
| 49 | + expect(input.value).toBe('$23.0') |
| 50 | +}) |
| 51 | + |
| 52 | +test('It should not allow letters to be inputted', () => { |
| 53 | + const {input} = setup() |
| 54 | + expect(input.value).toBe('') // empty before |
| 55 | + fireEvent.change(input, {target: {value: 'Good Day'}}) |
| 56 | + expect(input.value).toBe('') //empty after |
| 57 | +}) |
| 58 | + |
| 59 | +test('It should allow the $ to be deleted', () => { |
| 60 | + const {input} = setup() |
| 61 | + fireEvent.change(input, {target: {value: '23'}}) |
| 62 | + expect(input.value).toBe('$23') // need to make a change so React registers "" as a change |
| 63 | + fireEvent.change(input, {target: {value: ''}}) |
| 64 | + expect(input.value).toBe('') |
| 65 | +}) |
0 commit comments