jest单元测试失败,setData似乎不工作



我正在尝试学习单元测试我的vue应用程序通过以下教程。我设置了这个名为AppHeader的组件,其中包含一个按钮,该按钮仅在变量"loggedIn"是真的。

为了设置值"loggedIn"为true时,我使用. setdata来改变它的值。我使用setData不正确,还是有其他事情正在发生?

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);
});
});

输出:

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:UsersHPAppDataRoamingnpm-cache_logs2021-10-25T10_35_11_082Z-debug.log

我认为这里的问题可能是您正在更改数据,但现在等待下一个更改检测周期触发,这是异步发生的。

你可以等待setData来让这些变化像下面的例子一样解决(不要忘记将你的箭头函数设置为async),你也可以在这个关于测试异步组件的链接中进一步阅读,其中setData被提到作为可以等待的方法之一,也在setData的文档中。

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);
});

相关内容

  • 没有找到相关文章

最新更新