I'm trying to learn unit testing my vue application with jest by following a tutorial. I set up this component called AppHeader containing a button that is only visible when the variable "loggedIn" is true.
In order to set the value "loggedIn" to true, I use .setData to change its value. Am i using setData incorrectly or is there something else going on?
AppHeader:
<template>
<div>
<button v-show="loggedIn">Logout</button>
</div>
</template>
<script>
export default {
data() {
return {
loggedIn: false,
};
},
};
</script>
AppHeader.spec.js:
import AppHeader from "@/components/AppHeader.vue";
import { mount } from "@vue/test-utils";
describe("AppHeader", () => {
test("hide button when user is logged off", () => {
const wrapper = mount(AppHeader);
expect(wrapper.find("button").isVisible()).toBe(false);
});
test("show button when user is logged in", () => {
const wrapper = mount(AppHeader);
wrapper.setData({ loggedIn: true });
expect(wrapper.find("button").isVisible()).toBe(true);
});
});
output:
FAIL tests/unit/AppHeader.spec.js
AppHeader
√ hide button when user is logged off (23ms)
× show button when user is logged in (7ms)
● AppHeader › show button when user is logged in
expect(received).toBe(expected) // Object.is equality
Expected: true
Received: false
11 | const wrapper = mount(AppHeader);
12 | wrapper.setData({ loggedIn: true });
> 13 | expect(wrapper.find("button").isVisible()).toBe(true);
| ^
14 | });
15 | });
16 |
at Object.<anonymous> (tests/unit/AppHeader.spec.js:13:48)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 passed, 2 total
Snapshots: 0 total
Time: 2.85s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! music_gym@0.1.0 test:unit: `vue-cli-service test:unit`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the music_gym@0.1.0 test:unit script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\HP\AppData\Roaming\npm-cache\_logs\2021-10-25T10_35_11_082Z-debug.log
CodePudding user response:
I think the issue here may be that you are changing the data but now waiting for the next change detection cycle to trigger, this happens asynchronously.
You can await setData to let these changes settle as the following example (don't forget to set your arrow function as async), also you can further read about this in this link about testing asynchronous components where setData is mentioned as one of the methods that can be awaited and also in setData's documentation.
test("show button when user is logged in", async() => {
const wrapper = mount(AppHeader);
await wrapper.setData({ loggedIn: true });
expect(wrapper.find("button").isVisible()).toBe(true);
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>