开玩笑的单元测试失败,setData 似乎不起作用

jest unit tests failing, setData does not seem to be working

我正在尝试按照教程学习使用 jest 对我的 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:\Users\HP\AppData\Roaming\npm-cache\_logs21-10-25T10_35_11_082Z-debug.log

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

您可以像下面的示例一样等待 setData 让这些更改生效(不要忘记将箭头函数设置为异步),您也可以在 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.[=12= 中进一步阅读相关内容]

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