TypeError: attributes.item is not a function
See original GitHub issueSubject of the issue
I have a component that contains an image (<img />
) element.
When I execute a test with the following code:
const img = wrapper.find('img') // img element exists for 100%
img.trigger('load') // <- here error happens / error log points for this particular line
Steps to reproduce
Create any Vue component that contains img
element inside with binded @load="onImgLoad"
method for img
DOM element.
Create following test:
test('Should call onLoad after img load', async () => {
const onImgLoad = jest.fn();
const wrapper: Wrapper<any> = shallowMount(ImageComponent, {
methods: {
onImgLoad,
},
});
const img = wrapper.find('img');
await img.trigger('load');
expect(onImgLoad).toHaveBeenCalledTimes(1);
});
Expected behaviour
Test should pass just fine, load event should be triggered 1 time.
Actual behaviour
Test fails and throws an error:
TypeError: attributes.item is not a function
It also fails for other DOM elements (selected via wrapper.find()
), when I try to use .trigger
methods with other events on them.
Node version: v14.15.4
Vue-test-utils version: 1.0.0-beta.31
Using Vue 2 + Typescript
Possible Solution
I’ve updated the vue-test-utils.js
file inside my node_modules
folder (file url in the github repo: https://github.com/vuejs/vue-test-utils/blob/dev/packages/test-utils/src/wrapper.js )
In this method definition:
/**
* Returns an Object containing all the attribute/value pairs on the element.
*/
attributes(key?: string): { [name: string]: string } | string {
this.__warnIfDestroyed()
const attributes = this.element.attributes
const attributeMap = {}
for (let i = 0; i < attributes.length; i++) {
const att = attributes.item(i)
attributeMap[att.localName] = att.value
}
return key ? attributeMap[key] : attributeMap
}
I’ve replaced const att = attributes.item(i)
to const att = attributes[i]
and test started passing just fine.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:9 (2 by maintainers)
Top GitHub Comments
@lukaszkups Try using
jsdom
instead of@happy-dom/jest-environment
as your testEnvironment. It worked for me 😃This is the root cause: https://github.com/capricorn86/happy-dom/issues/308. Not fixed yet, but happy-dom has been having a lot of activity lately so maybe soon…