Comments (17)
Sorry, forgot to close this after merging #86.
Also thanks @fartek for the example, I've actually been a fan of using async/await in my tests, so I don't have to wrap anything in a callback:
it('should await synchronously', async () => {
const wrapper = mount(MyComponent)
await wrapper.vm.$nextTick()
// assert things like data loading properly
}
from vue-test-utils.
Doesn't work either:
await flushPromises()
await flushPromises()
expect(wrapper.find({ ref: 'emailField' }).text()).toBe('[email protected]')
edit: huh, this works though:
flushPromises().then(() => {
expect(wrapper.find({ ref: 'emailField' }).text()).toBe('[email protected]')
})
Any idea why the async/await version wouldn't work (I'm using async/await everywhere else in my code)? 🤔
from vue-test-utils.
We ran into a similar problem recently, this is what we found:
Instead of:
await wrapper.vm.$nextTick();
Use:
// mount your component
await new Promise(resolve => setTimeout(resolve));
// promise should resolved and you can assert things like data loading properly
instead.
from vue-test-utils.
Use flush-promises:
npm install --save-dev flush-promises
import flushPromises from 'flush-promises'
test('data is loaded and rendered', async () => {
const store = createNamespacedStore('@/store/modules/Profile', 'Profile')
const wrapper = mount(Profile, {
store,
localVue,
mocks: {
$t: jest.fn()
}
})
await flushPromises()
expect(wrapper.find({ ref: 'emailField' }).text()).toBe('[email protected]')
})
})
from vue-test-utils.
I can +1 on @chlab’s use–case, works for me as a then
able, unfortunately doesn’t with await
. 🤔
from vue-test-utils.
You can handle wrapper.vm.$nextTick
by using your test runner's done/end functions.
For instance with Ava you would write a test:
// use 'test.cb' instead of just 'test' as it tells Ava to wait for a callback
test.cb('A $nextTick test that will pass', t => {
const wrapper = shallow(MyComponent);
wrapper.vm.$nextTick(() => {
t.pass(); // passes the test - you can have any assertion here
t.end(); // ends the test
});
});
And other test runners also must have similar methods for testing async JS.
from vue-test-utils.
I expect people finding this works are getting a false positive:
flushPromises().then(() => {
expect(wrapper.find({ ref: 'emailField' }).text()).toBe('[email protected]')
})
This made my test pass but if I returned the promise in my jest test as my linter told me to do, then the test failed again as before:
return flushPromises().then(() => {
expect(wrapper.find({ ref: 'emailField' }).text()).toBe('[email protected]')
})
from vue-test-utils.
I'd be happy to, I'll try to get something up tonight.
from vue-test-utils.
Thanks for the issue 🙂
You're right, update
only re renders the DOM. It doesn't affect async functions, like promises.
I think this should be added to the docs. Would you like to make a PR clarifying that update
does not do this?
from vue-test-utils.
Sorry for posting this here, but I'm having trouble with this exact case. I am writing a test for a component that loads data from an API and displays that data in a form. I'm mocking the data access layer and resolving the promise right away. With the code above, the value is never there yet and my test fails.
Here's the test:
// ...imports
describe('Profile page', () => {
const localVue = createLocalVue()
localVue.use(Vuex)
// mock api data
jest.mock('@/data/PersonData', () => {
return {
getOwnerData () {
return Promise.resolve({ email: '[email protected]' })
}
}
})
test('data is loaded and rendered', async () => {
const store = createNamespacedStore('@/store/modules/Profile', 'Profile')
const wrapper = mount(Profile, {
store,
localVue,
mocks: {
$t: jest.fn()
}
})
await wrapper.vm.$nextTick()
// this fails:
expect(wrapper.find({ ref: 'emailField' }).text()).toBe('[email protected]')
// this passes:
setTimeout(() => {
expect(wrapper.find({ ref: 'emailField' }).text()).toBe('[email protected]')
}, 10)
})
})
Any help on this?
from vue-test-utils.
Thanks @eddyerburgh. Unfortunately, it still doesn't work. I have the await flushPromises()
right before the expect. Again, if I put the expect
into the setTimeout
block, even with 1ms, the test passes.
It may be relevant to note that the component I'm testing calls the mocked function getOwnerData()
in it's beforeMount
hook. So it's being invoked automatically. All the examples I'm seeing with jest are invoking the async methods themselves, like:
expect(wrapper.load()).resolves.toBe(...)
from vue-test-utils.
Try calling flushPromises twice.
Here's an example test for a component that runs an async function in beforeMount
—https://github.com/eddyerburgh/vue-hackernews-chapter-6/blob/master/src/views/__tests__/ItemList.spec.js#L65
from vue-test-utils.
@mixn What test runner/ browser environment are you using?
from vue-test-utils.
I've just been dealing with a similar problem and didn't want to hack around it using timeout's (nextTick
also didn't work). I fixed this by exposing the promise in my components data and referencing it in my test.
form.js
data () {
return {
submitPromise: true
}
},
methods: {
submit () {
this.submitPromise = this.$validator
.validateAll()
.then(() => {
if (!this.credentialsIncorrect && !this.errors.items.length) {
this.$emit('onCredentialsCorrect', this.activationForm)
} else {
this.$emit('onCredentialsIncorrect', this.errors.items)
}
return Promise.resolve()
})
return this.submitPromise
}
},
form.test.js
it('will run test after promise is resolved', () => {
form.trigger('submit')
return wrapper.vm.submitPromise
.then(()=>{
expect(wrapper.emitted('onCredentialsCorrect')).toBeTruthy()
})
})
from vue-test-utils.
Hi @chlab, thanks for you post. it saves my day.
flushPromises().then(() => {
expect(wrapper.find({ ref: 'emailField' }).text()).toBe('[email protected]')
})
from vue-test-utils.
wondering if including import 'babel-polyfill';
would help in @chlab 's case. 🤔
from vue-test-utils.
Doesn't work either:
await flushPromises() await flushPromises() expect(wrapper.find({ ref: 'emailField' }).text()).toBe('[email protected]')
edit: huh, this works though:
flushPromises().then(() => { expect(wrapper.find({ ref: 'emailField' }).text()).toBe('[email protected]') })
Any idea why the async/await version wouldn't work (I'm using async/await everywhere else in my code)?
Thanks @chlab . I had a same issue and this worked well.
from vue-test-utils.
Related Issues (20)
- `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. HOT 3
- `findComponent` doesn't find anything when using `@vue/compat` HOT 1
- Components with TS generic HOT 1
- event.keyCode is deprecated
- Change mocks mid-test
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.