在测试react reducer时,如何在第一次测试后忽略一个笑话mock



我正在使用react测试库

我在reducer中使用react cookie来加载用户。我想要mock-react cookie,这样我就可以在测试时将假用户加载到我的reducer中。然而,我只想在第一次测试中模拟react cookie,因为在第二次测试中,我希望cookie像react cookie的原始实现那样返回未定义的结果。所以我在测试中的mocks文件夹中有react cookie。所以我在嘲笑整个模块的react cookie。

但我希望第二次测试忽略我在嘲笑反应饼干。但我尝试过jest.RequireActual, jest.unmock, jest.deepUnmock,但这些都不起作用,而且我的测试总是使用react cookie的模拟实现。

测试文件:

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 cookie文件:

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

}

难道不能直接在测试中模拟它吗?类似于:

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
}))

最新更新