使用设置语法测试 Pinia 存储 - 如何模拟计算字段?

问题描述 投票:0回答:1

任何人都知道如何使用 @pinia/testingvitest 测试 Pinia 商店,如果我使用 setup 语法 进行商店。当我使用 createTestingPinia 时,我可以模拟计算字段,但无法识别操作。如果我仅使用 createPinia,我无法模拟计算字段,但可以识别存储操作。有人有类似的问题吗?非常感谢。

我尝试模拟计算字段(使用 createPinia 设置活动 Pinia):

const store = useStore(); store.someComputedField = computed(() => 1);

如果我使用 createTestingPinia,我可以像这样模拟它:

store.someComputedField = 1;

但是如果我尝试调用商店操作,它不会被识别。

我需要这个,因为我的操作使用来自同一商店的计算字段。一件重要的事情是,如果我使用标准存储语法,这不是问题。

unit-testing testing vuejs3 pinia vitest
1个回答
0
投票

摘自文档

// actions are stubbed by default, meaning they don't execute their code by default.
store.someAction()

这意味着您需要这样做,这样操作就不会被存根(但仍然会被监视):

const wrapper = mount(Counter, {
  global: {
    plugins: [createTestingPinia({ stubActions: false })],
  },
})

const store = useSomeStore()

// Now this call WILL execute the implementation defined by the store
store.someAction()

// ...but it's still wrapped with a spy, so you can inspect calls
expect(store.someAction).toHaveBeenCalledTimes(1)

我建议阅读doc,它写得很好,并且有关于如何测试您的商店的示例。

© www.soinside.com 2019 - 2024. All rights reserved.