测试Reactor时如何在首次测试后忽略玩笑模拟

时间:2020-07-22 20:19:08

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

我正在使用react-testing-library

我在我的减速器中使用react-cookies来加载用户。我想模拟react-cookies,以便在测试时可以将伪造的用户加载到我的reducer中。但是,我只想在第一个测试中模拟react-cookies,因为在第二个测试中,我希望cookie返回undefined,这是原始的react-cookies实现的。所以我在测试中的模拟文件夹中有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"
            })
       
}

1 个答案:

答案 0 :(得分:0)

您不能直接在测试中直接模拟它吗? 像这样:

AttributeError: module 'os' has no attribute 'uname' this error as well as this 
pipenv.patched.notpip._internal.exceptions.InstallationError:
Command errored out with exit status 1:
python setup.py egg_info Check the logs for full command output.

或者,您可以尝试以下操作:

import * as cookies from 'react-cookies';

cookies.load = jest.fn().mockImplementation(() => {
    name: 'Smith'
});

cookies.load.mockClear();