diff --git a/docs/api/wrapper-array/at.md b/docs/api/wrapper-array/at.md index a5b540317..d253a8538 100644 --- a/docs/api/wrapper-array/at.md +++ b/docs/api/wrapper-array/at.md @@ -1,6 +1,7 @@ ## at 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). - **Arguments:** @@ -16,6 +17,10 @@ import Foo from './Foo.vue' const wrapper = shallowMount(Foo) const divArray = wrapper.findAll('div') + const secondDiv = divArray.at(1) -expect(secondDiv.is('p')).toBe(true) +expect(secondDiv.is('div')).toBe(true) + +const lastDiv = divArray.at(-1) +expect(lastDiv.is('div')).toBe(true) ``` diff --git a/packages/test-utils/src/wrapper-array.js b/packages/test-utils/src/wrapper-array.js index 83458fb9c..4a4e22560 100644 --- a/packages/test-utils/src/wrapper-array.js +++ b/packages/test-utils/src/wrapper-array.js @@ -23,10 +23,13 @@ export default class WrapperArray implements BaseWrapper { } at(index: number): Wrapper | VueWrapper { - if (index > this.length - 1) { - throwError(`no item exists at ${index}`) + 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[index] + return this.wrappers[normalizedIndex] } attributes(): void { diff --git a/test/specs/wrapper-array/at.spec.js b/test/specs/wrapper-array/at.spec.js index 5d18bfe6e..9d474fa9b 100644 --- a/test/specs/wrapper-array/at.spec.js +++ b/test/specs/wrapper-array/at.spec.js @@ -13,6 +13,19 @@ describeWithShallowAndMount('at', mountingMethod => { expect(p.classes()).to.contain('index-1') }) + it('returns Wrapper at index from the end when index is negative', () => { + const TestComponent = { + template: '