我有一个看起来像这样的 utils 文件
// utils.js
const getNextDate = (startDate) => moment(startDate, 'MMM Do YYYY').startOf('day').add(10, 'days').format('MMM Do YYYY');
const getDisplayName = (user) => {
if (user.type === 'admin') {
return 'Admin';
} else if (user.type === 'guest') {
return 'Guest'
} else if(user.type === 'user') {
return `${user.firstname} ${user.lastname}`
} else {
return 'No user'
}
}
export {
getNextDate,
getDisplayName
}
我的 mocks 文件夹中还有一个 utils 文件的模拟,我在其中实现模拟返回值以进行测试。看起来像这样
// mock/utils.js
export const getNextDate = () => 'Oct 20th 2020';
export const getDisplayName = (user) => user
在我的组件和测试中,我正在做这样的事情
//Component.js
import React from 'react';
import { getNextDate, getDisplayName } from './utils'
export const Component = () => {
const user = {
type: 'admin',
firstname: 'john',
lastname: 'doe',
}
return (
<div>
<div>{getDisplayName(user)}</div>
<div>{getNextDate(moment())}</div>
</div>
)
}
// Component.test.js
import { Component } from '../Component'
jest.mock('./utils', () => require('./mock/utils'));
describe('Component', () => {
beforeEach(() => {
wrapper = shallow(
<Component />
);
});
it('renders next date', () => {
// At this point, I want to change the mock return value of getNextDate to Dec 25th 2020 without changing it in mock/utils.js as other tests are using that value
expect(wrapper.find('.date').text()).toEqual('Dec 25th 2020');
});
});
但是,在其中一个测试用例中,我尝试更改 getNextDate
的模拟实现。由于我无法直接调用 getNextDate.mockImplementation()
,因此如何完成此操作?
最佳答案
jest.mock('./utils', () => require('./mock/utils'))
重新发明了现有的 Jest 功能,__mocks__
manual mocks .
它应该是 __mocks__/utils.js
与原始模块处于同一级别,并使用 Jest spies 以使实现可更改:
export const getNextDate = jest.fn(() => ...);
export const getDisplayName = jest.fn(() => ...);
考虑到 __mocks__
提供了默认的模拟,因此对于特定测试,不应使用 mockImplementation
覆盖它们,因为这会影响后续测试。相反,应该使用 *Once
来模拟特定调用。对于在 beforeEach
中指定且对多个测试通用的包装器:
import { getNextDate } from './utils';
jest.mock('./utils')
...
beforeEach(() => {
wrapper = shallow(<Component />); // uses default mock
});
it('renders next date', () => {
getNextDate.mockReturnValueOnce(...);
wrapper.setProps({}); // update with new mock
expect(wrapper.find('.date').text()).toEqual('Dec 25th 2020');
});
关于javascript - 如何更改 Jest 中模拟模块中函数的模拟实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64350855/