diff --git a/docs/api/wrapper-array/at.md b/docs/api/wrapper-array/at.md index d253a8538..dabcd5082 100644 --- a/docs/api/wrapper-array/at.md +++ b/docs/api/wrapper-array/at.md @@ -2,6 +2,7 @@ Returns `Wrapper` at `index` passed. Uses zero based numbering (i.e. first item is at index 0). If `index` is negative, indexing starts from the last element (i.e. last item is at index -1). +When none is found, returns an `ErrorWrapper`. - **Arguments:** @@ -23,4 +24,7 @@ expect(secondDiv.is('div')).toBe(true) const lastDiv = divArray.at(-1) expect(lastDiv.is('div')).toBe(true) + +const nonExistentDiv = divArray.at(1000) +expect(nonExistentDiv.exists()).toBe(false) ``` diff --git a/packages/test-utils/src/wrapper-array.js b/packages/test-utils/src/wrapper-array.js index 12ca36844..0c4d540b6 100644 --- a/packages/test-utils/src/wrapper-array.js +++ b/packages/test-utils/src/wrapper-array.js @@ -3,6 +3,7 @@ import type Wrapper from './wrapper' import type VueWrapper from './vue-wrapper' import { throwError } from 'shared/util' +import ErrorWrapper from './error-wrapper' export default class WrapperArray implements BaseWrapper { +wrappers: Array @@ -23,14 +24,9 @@ export default class WrapperArray implements BaseWrapper { }) } - at(index: number): Wrapper | VueWrapper { + at(index: number): Wrapper | VueWrapper | ErrorWrapper { const normalizedIndex = index < 0 ? this.length + index : index - if (normalizedIndex > this.length - 1 || normalizedIndex < 0) { - let error = `no item exists at ${index}` - error += index < 0 ? ` (normalized to ${normalizedIndex})` : '' - throwError(error) - } - return this.wrappers[normalizedIndex] + return this.wrappers[normalizedIndex] || new ErrorWrapper('') } attributes(): void { diff --git a/test/specs/wrapper-array/at.spec.js b/test/specs/wrapper-array/at.spec.js index 6862390f7..da2dc8915 100644 --- a/test/specs/wrapper-array/at.spec.js +++ b/test/specs/wrapper-array/at.spec.js @@ -26,33 +26,12 @@ describeWithShallowAndMount('at', mountingMethod => { expect(first.classes()).to.contain('index-first') }) - it('throws error if no item exists at index', () => { - const index = 2 + it('returns ErrorWrapper at index when not found', () => { const TestComponent = { - template: '

' + template: '
' } - const message = `[vue-test-utils]: no item exists at ${index}` - expect(() => - mountingMethod(TestComponent) - .findAll('p') - .at(index) - ) - .to.throw() - .with.property('message', message) - }) - - it('throws error if no item exists at negative index', () => { - const index = -3 - const TestComponent = { - template: '

' - } - const message = `[vue-test-utils]: no item exists at -3 (normalized to -1)` - expect(() => - mountingMethod(TestComponent) - .findAll('p') - .at(index) - ) - .to.throw() - .with.property('message', message) + const all = mountingMethod(TestComponent).findAll('p') + const nonExistent = all.at(0) + expect(nonExistent.exists()).to.equal(false) }) })