【问题标题】:How to ignore a jest mock after the first test when testing react reducer测试reducer时如何在第一次测试后忽略一个笑话
【发布时间】:2020-11-12 11:43:28
【问题描述】:

我正在使用 react-testing-library

我在 reducer 中使用 react-cookies 来加载用户。我想模拟 react-cookies,所以我可以在测试时将假用户加载到我的减速器。但是,我只想在第一个测试中模拟 react-cookies,因为在第二个测试中,我希望 cookie 返回 undefined,这与 react-cookies 的原始实现相同。所以我在我的测试中的 mocks 文件夹中有 react-cookies。所以我在嘲笑整个模块 react-cookies。

但我希望第二次测试忽略我在嘲笑 react-cookies。但是我尝试了jest.RequireActual, jest.unmock, jest.deepUnmock,但这些都不起作用,我的测试总是使用 react-cookies 的模拟实现。

测试文件:

describe('reducer', () => {
  afterEach(() => {jest.unmock('react-cookies')  });

  test('should return initialState when user is defined ', () => {
    expect(authentication(undefined, {})).toEqual(
      {
        user: {
         name: "Smith",
        },
      })
  })

  test('should return initialState when user is undefined', () => {
    expect(authentication(undefined, {})).toEqual(
      {
        user: undefined,
      }
    )
  })
})

这是 mocks 文件夹中的 react-cookies 文件:

export default {
    load: jest.fn()
    .mockReturnValue(
          {
                name: "Smith"
            })
       
}

【问题讨论】:

    标签: reactjs react-redux react-testing-library


    【解决方案1】:

    你不能直接在你的测试中模拟它吗? 比如:

    import * as cookies from 'react-cookies';
    
    cookies.load = jest.fn().mockImplementation(() => {
        name: 'Smith'
    });
    
    cookies.load.mockClear();
    

    或者,你可以试试这个:

    jest.mock('react-cookies', () => ({
      load: jest.fn() //and mock implementation if you wish
    }))
    

    【讨论】:

    • 我收到一个错误,因为 cookies.load.mockClear(); 不是函数,当我以这种方式模拟函数时,测试不会运行模拟函数
    • 还有其他方法可以模拟 cookies.load 吗?
    • 加载用户时,reducer 中仍然未定义
    • 当我将模拟函数放在我的描述语句之外时它可以工作,但是对于第二次测试我想删除模拟
    • 如上所述,测试后恢复mock
    猜你喜欢
    • 1970-01-01
    • 2012-08-14
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 2018-12-17
    • 2018-12-19
    相关资源
    最近更新 更多