1

我创建了一个使用商店中的 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('/');
  });
})

我从这个例子中得到启发。

4

1 回答 1

2

感谢@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('/');
  });
})
于 2021-10-15T12:49:28.593 回答