如何通过使用打字稿在 beforeEach 挂钩中安装 Vue 组件来干燥代码?

Posted

技术标签:

【中文标题】如何通过使用打字稿在 beforeEach 挂钩中安装 Vue 组件来干燥代码?【英文标题】:How can I DRY up the code by mounting Vue component in the beforeEach hook using typescript? 【发布时间】:2022-01-08 13:49:44 【问题描述】:

这是我的代码。我想把这个案子擦干。

describe("Stored id", () => 

  it("ID empty", () => 

    // when
    const wrapper = mount(SigninPage, options);
    const vm = wrapper.vm;

  );

  it("ID exist", () => 

    // when
    localStorage.setItem(process.env.VUE_APP_SIGNIN_STORED_USER_ID, STORED_ID);
    const wrapper = mount(SigninPage, options);
    const vm = wrapper.vm;

  );

);

如何像使用 typescript 一样使用 beforeEach 钩子?

我想使用 beforeEach 钩子。但由于 tsc,我无法运行测试。我认为当变量类型正确时才有可能。

describe("Stored id", () => 

  // problem
  let wrapper: VueWrapper<??>;
  let vm: ??;

  beforeEach(() => 
    wrapper = mount(SigninPage);
    vm = wrapper.vm;
  );

  it("ID empty", () => 

    // const wrapper = mount(SigninPage, options);
    // const vm = wrapper.vm;

  );

  it("ID exist", () => 

    // Should I save it before the wrapper is mounted?
    localStorage.setItem(process.env.VUE_APP_SIGNIN_STORED_USER_ID, STORED_ID);
    // const wrapper = mount(SigninPage, options);
    // const vm = wrapper.vm;

  );

);

【问题讨论】:

【参考方案1】:

自我回答。我是这样处理的。

describe("Header", () => 

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  let wrapper: VueWrapper<any>;

  const code = "A005930";
  const options =  propsData:  code  ;

  beforeEach(async () => 
    wrapper = shallowMount(Header, options);
  );

  it("should have stored data set", async () => 
    const mockQueryParams =  code: "A005930", page: 0, size: 100 ;
    await store.fetchPriceData(mockQueryParams);
    // ...
  );

  // ...

【讨论】:

以上是关于如何通过使用打字稿在 beforeEach 挂钩中安装 Vue 组件来干燥代码?的主要内容,如果未能解决你的问题,请参考以下文章

如何通过打字稿在Vue2中使用带有组合api的vue类组件

如何使用打字稿在reactjs中传递数据

如何使用打字稿在表格的单元格中动态插入锚标记?

使用打字稿在reduce方法中使用扩展语法进行解构

如何使用打字稿在angular2中获取设备显示的高度和宽度?

如何使用打字稿在 gulp-angular-generator 中定义指令