在测试之间更改Jest模拟值

时间:2019-08-12 15:54:20

标签: javascript unit-testing vue.js mocking jestjs

我有一个实用程序文件,该文件通过vuex存储使用以下实现:

sentinel monitor MatserRedis redis_node 6000 3
sentinel down-after-milliseconds MatserRedis 3000
sentinel failover-timeout MatserRedis 10000
sentinel parallel-syncs MatserRedis 1

在测试中,我发现可以通过以下两种方式成功模拟// example.js import store from '@/store'; [...] export default function exampleUtil(value) { const user = store.state.user.current; [...] } 的值:

手动模拟

user

模拟功能

// store/__mocks__/index.js

export default {
  state: {
    user: {
      current: {
        roles: [],
        isAdmin: false,
      },
    },
  },
};

我遇到的问题是我希望能够在两次测试之间更改// example.spec.js jest.mock('@/store', () => ({ state: { user: { current: { roles: [], isAdmin: false, }, }, }, })); 的值,例如将current更改为true或为{{1}更新数组}。

使用Jest模拟实现此目的的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

事实证明,在导入模拟文件后,可以直接在测试中更改模拟值。

使用上面的模拟函数示例:

// example.spec.js

import store from '@/store'; // <-- add this

jest.mock('@/store', () => ({
  state: {
    user: {
      current: {
        roles: [],
        isAdmin: false,
      },
    },
  },
}));

it('should do things', () => {
  store.state.user.current.roles = ['example', 'another']; // <-- change mock value here
  [...]
});
相关问题