Vuex with Jest - this.$store.getters.<getterName> 不是函数

Rob*_*ood 3 vue.js jestjs vuex

我正在 Vue 中开发一个调查构建器,用户创建的调查问题提交给 Vuex,以便以后可以像这样检索它们:

computed: {
  inputs() {
    return this.$store.getters.questions(this.pageNumber);
  },
},
Run Code Online (Sandbox Code Playgroud)

pageNumber是组件接收并inputs()返回一系列问题的道具。这一切似乎都可以在屏幕上呈现正确的问题,但我在 Jest 测试中遇到了麻烦。

为了进行测试,我希望我可以像下面的尝试一样使用 getter 来模拟商店(省略某些部分):

const localVue = createLocalVue();
localVue.use(Vuex);

beforeEach(() => {
  state = {
    survey: {
      pages: [
        // pages objects
      ],
    },
  };

  getters = {
    questions: () => [
      { type: 'Radio', config: { label: 'Test label', options: [{ label: 'Test option label' }] }, validation: [] },
    ],
  };

  store = new Vuex.Store({
    state,
    getters,
  });
});
Run Code Online (Sandbox Code Playgroud)

但这会导致错误:

TypeError: this.$store.getters.questions is not a function
Run Code Online (Sandbox Code Playgroud)

但是,从 getters.questions 中删除该箭头函数给了我:

[vuex] getters should be function but "getters.questions" is [{"type":"Radio","config":{"label":"Test label","options":[{"label":"Test option label"}]},"validation":[]}].
Run Code Online (Sandbox Code Playgroud)

所以我想我可能完全误解了。有人能指出我正确的方向吗?

ski*_*tle 11

store 的 getter 就像组件上的计算属性,它们是使用函数定义的,但作为属性访问,没有括号。

鉴于这一行:

return this.$store.getters.questions(this.pageNumber);
Run Code Online (Sandbox Code Playgroud)

看起来你的questionsgetter 正在返回一个接受 a 的函数pageNumber。这不是您当前在测试 getter 中定义的内容,您只是返回一个数组。

因此,调用需要更改为使用方括号:

return this.$store.getters.questions[this.pageNumber];
Run Code Online (Sandbox Code Playgroud)

或者 getter 需要返回一个函数:

getters = {
    questions: () => () => [
        { type: 'Radio', config: { label: 'Test label', options: [{ label: 'Test option label' }] }, validation: [] }
    ]
};
Run Code Online (Sandbox Code Playgroud)

如果它有助于澄清,这相当于:

getters = {
    questions: function () {
        return function () {
            const questions = [
                { type: 'Radio', config: { label: 'Test label', options: [{ label: 'Test option label' }] }, validation: [] }
            ];

            return questions;
        };
    }
};
Run Code Online (Sandbox Code Playgroud)

请注意,我完全忽略了通过,pageNumber因为我假设您的测试 getter 是硬编码的以返回正确的问题数组。

您可能希望咨询此 getter 的非测试版本,因为我希望您会看到它返回一个额外的函数级别。