Jest.js 当模拟组件内部的自定义钩子时返回不同的对象值[关闭]

6ioyuze2  于 6个月前  发布在  Jest
关注(0)|答案(1)|浏览(83)

**已关闭。**此问题需要debugging details。目前不接受回答。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答问题。
7天前关闭
Improve this question
我在这里有两个描述语法,第一个是当用户没有登录时,第二个是当用户登录时。但不知何故,我认为我以一种错误的方式模仿了这两个相互影响的返回值。我还写了clearAllMocks()函数,但它没有帮助。

describe('Header Login', () => {
  beforeEach(() => {
    vi.mock('@/hooks/useAuth', () => ({
      useAuth: vi.fn().mockReturnValue({
       isLoggedIn: false,
      })
    }))

    render(<Header/>)
    )
  })  

  afterAll(() => vi.clearAllMocks())

  test('should show Login button while not logged in', async () => {
    expect(screen.getByRole('button', { name: /login/i })).toBeInTheDocument()
  })

})

describe('Header Logout', () => {
  beforeEach(() => {
    vi.mock('@/hooks/useAuth', () => ({
      useAuth: vi.fn().mockReturnValue({
       isLoggedIn: true,
      })
    }))

    render(<Header/>)
  })   

  afterAll(() => vi.clearAllMocks())

  test('should show Logout button in case user is logged in', async () => {
    expect(screen.getByRole('button', { name: /logout/i })).toBeInTheDocument()
  })
})

字符串

1wnzp6jl

1wnzp6jl1#

尝试这段代码,我修改了一些东西,比如我用afterEach替换了afterAll,并在每次测试后使用vi. clearMocks()代替vi.clearAllMocks()。

describe('Header Login', () => {
  beforeEach(() => {
    vi.mock('@/hooks/useAuth', () => ({
      useAuth: vi.fn().mockReturnValue({
        isLoggedIn: false,
      }),
    }));

    render(<Header />);
  });

  afterEach(() => {
    vi.clearMocks(); // Clear mocks after each test
  });

  test('should show Login button while not logged in', async () => {
    expect(screen.getByRole('button', { name: /login/i })).toBeInTheDocument();
  });
});

describe('Header Logout', () => {
  beforeEach(() => {
    vi.mock('@/hooks/useAuth', () => ({
      useAuth: vi.fn().mockReturnValue({
        isLoggedIn: true,
      }),
    }));

    render(<Header />);
  });

  afterEach(() => {
    vi.clearMocks(); // Clear mocks after each test
  });

  test('should show Logout button in case the user is logged in', async () => {
    expect(screen.getByRole('button', { name: /logout/i })).toBeInTheDocument();
  });
});

字符串

相关问题