Skip to content

Commit cae1a50

Browse files
committed
feat(wrapper array): Allow negative indices to be passed to .at()
Passing a negative index to .at() lets you retrieve elements by starting from the end of the wrapper array (i.e. last item is at index -1)
1 parent 99336c4 commit cae1a50

File tree

3 files changed

+36
-2
lines changed

3 files changed

+36
-2
lines changed

Diff for: docs/api/wrapper-array/at.md

+6-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
## at
22

33
Returns `Wrapper` at `index` passed. Uses zero based numbering (i.e. first item is at index 0).
4+
If `index` is negative, indexing starts from the last element (i.e. last item is at index -1).
45

56
- **Arguments:**
67

@@ -16,6 +17,10 @@ import Foo from './Foo.vue'
1617

1718
const wrapper = shallowMount(Foo)
1819
const divArray = wrapper.findAll('div')
20+
1921
const secondDiv = divArray.at(1)
20-
expect(secondDiv.is('p')).toBe(true)
22+
expect(secondDiv.is('div')).toBe(true)
23+
24+
const lastDiv = divArray.at(-1)
25+
expect(lastDiv.is('div')).toBe(true)
2126
```

Diff for: packages/test-utils/src/wrapper-array.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ export default class WrapperArray implements BaseWrapper {
2323
}
2424

2525
at(index: number): Wrapper | VueWrapper {
26-
if (index > this.length - 1) {
26+
index = index < 0 ? this.length + index : index
27+
if (index > this.length - 1 || index < 0) {
2728
throwError(`no item exists at ${index}`)
2829
}
2930
return this.wrappers[index]

Diff for: test/specs/wrapper-array/at.spec.js

+28
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,19 @@ describeWithShallowAndMount('at', mountingMethod => {
1313
expect(p.classes()).to.contain('index-1')
1414
})
1515

16+
it('returns Wrapper at index from the end when index is negative', () => {
17+
const TestComponent = {
18+
template: '<div><p class="index-first" /><p class="index-last"/></div>'
19+
}
20+
const all = mountingMethod(TestComponent).findAll('p')
21+
const last = all.at(-1)
22+
const first = all.at(-2)
23+
expect(last.vnode).to.be.an('object')
24+
expect(last.classes()).to.contain('index-last')
25+
expect(first.vnode).to.be.an('object')
26+
expect(first.classes()).to.contain('index-first')
27+
})
28+
1629
it('throws error if no item exists at index', () => {
1730
const index = 2
1831
const TestComponent = {
@@ -27,4 +40,19 @@ describeWithShallowAndMount('at', mountingMethod => {
2740
.to.throw()
2841
.with.property('message', message)
2942
})
43+
44+
it('throws error if no item exists at negative index', () => {
45+
const index = -3
46+
const TestComponent = {
47+
template: '<div><p /><p class="index-1"/></div>'
48+
}
49+
const message = `[vue-test-utils]: no item exists at -1`
50+
expect(() =>
51+
mountingMethod(TestComponent)
52+
.findAll('p')
53+
.at(index)
54+
)
55+
.to.throw()
56+
.with.property('message', message)
57+
})
3058
})

0 commit comments

Comments
 (0)