问题
I have an error when trying to perform a unit test with Jest on a component in VueJs that has an animation made with TweenMax GSAP
.
The error is: Cannot tween a null target.
in ztButton.spec.js
jest.mock('gsap/TweenMax')
it('Component must to emit event on click', () => {
const wrapper = shallowMount(ztButton)
const spy = sinon.spy()
wrapper.setMethods({ clickButton: spy })
wrapper.find('.zt-button').trigger('click')
expect(spy.called).toBe(true)
})
in my project directory
in TweenMax.js of mock directory
module.exports = {
TweenMax: class {
static to(selector, time, options) {
return jest.fn()
}
}
}
in test directory
There is something I do not understand, or that I am not doing well. Something confused.
Update: This is what I do to generate an animation in my component and is invoked in mounted
mounted() {
this.componentId = this._uid
this._addButtonRipple()
},
methods: {
_addButtonRipple() {
const $button = this.$refs.button
$button.addEventListener('click', event => {
const rect = $button.getBoundingClientRect(),
x = event.clientX - rect.left,
y = event.clientY - rect.top
let $ripple = $button.querySelector('.zt-button-ripple')
TweenMax.set($ripple, {
x: x,
y: y,
scaleX: 0,
scaleY: 0,
opacity: 1
})
TweenMax.to($ripple, 1.5, {
scaleX: 1,
scaleY: 1,
opacity: 0,
ease: Expo.easeOut
})
})
},
clickButton(event) {
this.$emit('click', event)
this.isRipple = true
setTimeout(() => {
this.isRipple = false
}, 300)
}
}
in computed
computed: {
listeners() {
return {
...this.$listeners,
click: event => this.clickButton(event)
}
}
in html tags
<button v-on="listeners"></button>
this is the configuration of my file jest.config.js
module.exports = {
verbose: true,
moduleFileExtensions: ['js', 'jsx', 'json', 'vue'],
transform: {
'^.+\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$':
'jest-transform-stub',
'^.+\\.jsx?$': 'babel-jest'
},
transformIgnorePatterns: ['/node_modules/'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
'^src/(.*)$': '<rootDir>/src/$1',
'^src/component/(.*)$': '<rootDir>/src/components/atomic/$1'
},
snapshotSerializers: ['jest-serializer-vue'],
testMatch: [
'**/tests/unit/components/atomic/**/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
],
testURL: 'http://localhost/'
}
回答1:
Cannot tween a null target
means that TweenMax methods are not mocked. Infact you are mocking just TweenMax.to
method.
Please update your mock this way:
module.exports = {
TweenMax: class {
static to(selector, time, options) {
return jest.fn()
}
static set(selector, options) {
return jest.fn()
}
}
}
Let me know if that fixes it.
来源:https://stackoverflow.com/questions/59093137/error-cannot-tween-a-null-target-in-unit-test-with-gsap-tweenmax-jest-and-vuejs