Comments (9)
There's now a setMethods
method.
We should have a setComputed method too. I've created a new issue for that:
from vue-test-utils.
We could recommend this pattern:
const clickHandlerStub = sinon.stub()
wrapper.stubMethod('clickHandler', clickHandlerStub)
...
expect(clickHandlerStub.called).to.equal(true)
Or this:
const clickHandlerStub = sinon.stub()
wrapper.stubMethods({
clickHandler: clickHandlerStub
})
from vue-test-utils.
setMethods
worked great.
like here:
const spy = jest.spyOn(wrapper.vm, 'handleChange')
wrapper.setMethods({ handleChange: spy })
wrapper.find('.some-input').trigger('change')
expect(spy).toHaveBeenCalled()
from vue-test-utils.
I previously had a hook that was called before the component was mounted, which exposed a deep copy of the component so you could manually stub it's methods (without affecting the original component). But i actually really like your approach, I think it's really simple.
A couple of thoughts:
- would you want the option to restore a stubbed method at a later point?
- could you stub a method without having to provide an alternate function
{clickHandler:true}
- what about computed properties? There have been times when a method relies on a computed property that is so complicated it's taken me far outside the purpose of my unit test just to get the right computed value!
from vue-test-utils.
I prefer setMethods as it is consistent with setData and setProps. However, I think there should also be a method to retrieve them as it could be confusing that you then have to use the vm to check if it has been called.
wrapper.stubMethod(clickHandler, sinon.stub())
...
expect(wrapper.vm.clickHandler.called).to.equal(true)
With the current way, at least the way you set and get is consistent.
wrapper.vm.clickHandler = sinon.stub()
...
expect(wrapper.vm.clickHandler.called).to.equal(true)
from vue-test-utils.
would you want the option to restore a stubbed method at a later point?
I don't think so, with stubMethod
you could save the original before stubbing and then restore it later with the same method.
could you stub a method without having to provide an alternate function {clickHandler:true}
Yes I think that's a good idea
what about computed properties?
Yes I think that a setComputed
method would be a good idea if setData
does not work for a use case. Would you be able to provide example where setData
doesn't work, so I can use it as a test case?
from vue-test-utils.
@eddyerburgh those both look great 👍
That pattern also allows some of the useful sinon methods to be called on the stub without reaching directly into the vm.
i.e.
clickhandlerStub.resetHistory()
stubMethods could be quite useful for larger components with multiple methods that need to be stubbed.
const methods = {
foo: sinon.stub().returns(3),
bar: sinon.stub(),
baz: sinon.stub().throws("TypeError")
}
wrapper.stubMethods(methods)
...
expect(methods.foo).to.be.calledOnce
expect(methods.bar).to.be.calledTwice
from vue-test-utils.
Hi All,
const spy = sinon.stub()
wrapper.setMethods({ onClickCreate: spy })
wrapper.find('#btn-create-proposal').trigger('click')
expect(spy.called).toBe(true)
this is not working.
In Actual the method defined in component being mounted is being called.
Thanks for help in advance
from vue-test-utils.
Hey guys,
Hey guys, I have this file picker component that I am trying to test. The component receives the file through the takeFile
method.
<script lang="ts">
import { defineComponent, ref } from '@nuxtjs/composition-api'
import AppButtonCard from '~/components/Button/AppButtonCard.vue'
export default defineComponent({
components: {
AppButtonCard
},
setup (_props, { emit }) {
const isDraging = ref(false)
const openFilePicker = () => {
(document.querySelector('#file-upload') as any).click()
}
const handleSelectedFiles = (e: any) => {
const file = takeFile(e)
if (isValidFile(file)) {
emit('getFile', file)
} else {
emit('invalidFile')
}
}
const takeFile = (e: any) => {
return e.dataTransfer ? [...e.dataTransfer.files][0] : e.target.files[0]
}
const isValidFile = (file: File) => {
try {
const acceptedSuffixTypes = ['pdf', 'epub', 'txt', 'docx', 'rtf']
const fileName = file.name
const dot = fileName.lastIndexOf('.')
const suffix = fileName.substr(dot + 1)
if (acceptedSuffixTypes.includes(suffix)) {
return true
} else {
return false
}
} catch (_) {
return false
}
}
return {
openFilePicker,
handleSelectedFiles,
isDraging
}
}
})
</script>
I am trying to mock the takeFile method so that when it is called, it uses the mocked file. I am making use of sinon. But it seems the fileis not getting into the component.
import { mount } from '@vue/test-utils'
import sinon from 'sinon'
import FileUpload from './FileUpload.vue'
describe('~/components/Files/FileUpload.vue', () => {
it('it emits an error when an invalid file is picked.', () => {
const invalidFile = {
name: 'image.png',
size: 2887225,
type: 'image/jpeg',
lastModified: 1639671510625,
lastModifiedDate: 'Thu Dec 16 2021 17:18:30 GMT+0100 (West Africa Standard Time)'
}
const takeFile = sinon.fake.returns(invalidFile)
const wrapper = mount(FileUpload, {
mocks: {
takeFile
}
})
const fileInput = wrapper.find('input[type="file"]')
fileInput.trigger('change')
expect(wrapper.emitted().invalidFile).toBeDefined()
})
it('it emits the file when the file is valid and has been processed.', () => {
const validFile = {
name: 'document.pdf',
size: 2887225,
type: 'application/pdf',
lastModified: 1639671510625,
lastModifiedDate: 'Thu Dec 16 2021 17:18:30 GMT+0100 (West Africa Standard Time)'
}
const takeFile = sinon.fake.returns(validFile)
const wrapper = mount(FileUpload, {
mocks: {
takeFile
}
})
const fileInput = wrapper.find('input[type="file"]')
fileInput.trigger('change')
expect(wrapper.emitted().getFile).toBe([[validFile]])
})
})
Please, I urgently need help with this.
I have tried this and it's not working.
I think it's because I am using the composition API and I think this should work in the options API
I have also tried accessing the takeFile method directly like this
wrapper.vm.takeFile = sinon.fake.returns(validFile)
from vue-test-utils.
Related Issues (20)
- testing a child component inside a parent slot
- Composables are not being mocked in Vitest HOT 10
- When setProps() is called on a wrapper which renders a slot, the slot's content element gets destroyed
- `RouterLink.useLink` is missing when using `RouterLinkStub`. HOT 3
- Test child component, which is the root element HOT 3
- Computed value does not update when data updates
- isVisible() not seeing display: none using vitest with jsdom HOT 4
- Testing component with onBeforeRouteLeave hook raising "No active route record was found" warning HOT 1
- vue2 引入 element2. 页面存在table 表格 jest 测试报错 HOT 1
- *.svg?inline issues
- Errors in `setup()` are silent if `render()` throws an error HOT 6
- Check style changes on hover HOT 1
- setData on writable computed property does not seem to work as it does in VTU.1
- classes documentation
- Support Vue 2.7.16 HOT 2
- Vue test utils not updating template when testing composables
- TypeError: $setup.mergeProps is not a function
- Data property is already defined in Props. HOT 1
- Unable to use vitest spy within vue/nuxt 3 component methods.
- `findComponent` doesn't find anything when using `@vue/compat` HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from vue-test-utils.