【问题标题】:mock store getters inside Global Guard does not workGlobal Guard 中的模拟商店吸气剂不起作用
【发布时间】:2021-12-03 14:21:38
【问题描述】:

我创建了一个使用 store 中的 getter 的全局守卫。

我试图从商店模拟一些吸气剂以进行测试。问题是嘲笑

不工作。

// router/index.ts
export function beforeEach(to: any, from: any, next: any) {
  const isLoggedIn = store.getters.isLoggedIn();
  const isGuest = to.matched.some((record: any) => (record.meta.guest));
  if (isLoggedIn) { // isLoggedIn is always false
    if (isGuest) {
      next('/');
    }
  } 
  }
}
//router/index.spec.ts
describe('shoud test routing functionality', () => {
it('should redirect to / when isLoggedIn is true and IsGuest is true', () => {
    // given
    jest.mock('@/store', () => ({
      getters: {
        isLoggedIn: jest.fn().mockImplementation(
          () => true, // <----------- this value is always false
        ),
      },
    }));

     // even this one does not work
     //  jest.spyOn(getters, 'isLoggedIn').mockImplementation(() => 
     //  ()=> true);

    const to = {
      matched: [{ meta: { guest: true } }],
    };
    const next = jest.fn();

    // when
    beforeEach(to, undefined, next);

    // then
    expect(next).toHaveBeenCalledWith('/');
  });
})

我的灵感来自这个example

【问题讨论】:

  • 测试中的 jest.mock 不会影响顶级导入。

标签: vue.js jestjs vuex vue-test-utils vue-testing-library


【解决方案1】:

感谢@EstusFlask 的评论,我解决了这个问题。

关键字是 测试中的 jest.mock 不会影响顶级导入

jest.mock('@/store', () => ({
  getters: {
    isLoggedIn: jest.fn(),
  // other methods should be declared here, otherwise an exception is thrown
    isSuperAdmin: jest.fn(),
    isAdmin: jest.fn(),
    isReadUser: jest.fn(),
  },
}));

describe('should test routing functionality', () => {
   it('should redirect to / when isLoggedIn is true and IsGuest is true', () => {
    // given
    store.getters.isLoggedIn.mockImplementation(() => () => false);
    const to = {
      matched: [{ meta: { guest: true } }],
    };
    const next = jest.fn();

    // when
    beforeEach(to, undefined, next);

    // then
    expect(next).toHaveBeenCalledWith('/');
  });
})

【讨论】:

  • 很高兴它有帮助。顺便说一句 automock jest.mock('@/store') 做你想做的事,用存根替换所有函数。
猜你喜欢
  • 2021-10-04
  • 1970-01-01
  • 2019-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 2021-11-05
  • 2017-01-26
相关资源
最近更新 更多