我有一个看起来像这样的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()
,怎么办呢?
答案 0 :(得分:2)
for p,l,c,ax in zip(px,labels,colors,axs.flatten()):
ax.plot(t, p, color = c, label = l)
ax.set(xlim=[min(t),max(t)+1], ylim=[min(p), max(p)], ylabel = 'PgC')
ax.legend()
fig.tight_layout()
plt.figtext(0.55,0,'Year')
plt.savefig(filename,bbox_inches='tight')
plt.show()
重塑了现有的Jest功能__mocks__
manual mocks。
应该与原始模块处于同一级别,jest.mock('./utils', () => require('./mock/utils'))
并使用Jest间谍才能使实现可变:
__mocks__/utils.js
考虑到export const getNextDate = jest.fn(() => ...);
export const getDisplayName = jest.fn(() => ...);
提供了默认的模拟,对于特定的测试,它们不应被__mocks__
覆盖,因为这会影响后续的测试。相反,应使用mockImplementation
模拟特定调用。对于*Once
中指定的包装,它对于多个测试是通用的:
beforeEach