我基本同意@Alex。
但通常,与其总是将数据移动到不同的文件,我更愿意将真实的 API 模拟数据保留在测试文件本身中的一个特定案例中。
我将它们视为 React Components 的 PropType 部分,将它们保留在测试文件的按钮处(__test__、__spec__、*test.js 或 *.spec.js)但在文件中,除非我必须这样做分享。
这里有一个超级简单的 axios 示例:
src/__mocks__/axios.js
export default {
get: jest.fn(() => Promise.resolve({ data: [] })),
};
然后 axios 被模拟,因为现在如果我们想测试一个超级简单的包装 API 实用程序,例如:
import Axios from 'axios';
export const yourMethod = async () => {
return new Promise(resolve => {
Axios.get(`yourAPIEndPoint`)
.then(result => {
resolve([...result.data]);
})
.catch(e => {
console.error('should treat the error', e);
});
});
};
对我来说,一项测试只能是:
import Axios from 'axios';
import { yourMethod } from './borrame';
describe('yourMethod TestCase', () => {
it('it returns the data you expect', async () => {
// Specific response for this test case.
Axios.get.mockImplementationOnce(() =>
Promise.resolve({
data: yourMethodMockData,
})
);
const result = await yourMethod();
expect(result[0].id).toBe(yourMethodRawMockData[0].id);
});
});
/**
* Specific Test Data
*/
const yourMethodMockData = [
{
id: '12345',
name: 'Name for 12345',
},
];
即使,如果要在测试文件之外重用相同的模拟数据,我也会将此模拟数据移动到 __test__ 文件夹内的不同 .js 并将其导出以供重用。
当我必须根据 API 调用参数“生成”.json 数据时,我什至创建了mockAPIGenerators,但对我来说,遵循的一般规则始终是KIS
所以在同一个测试文件中将按钮作为常量,除非它对你来说还不够?。