我有一个看起来像这样的 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
}
我的 utils 文件中也有一个模拟mocks我在其中实现模拟返回值以进行测试的文件夹。它看起来像这样
// 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()
直接地?