我正在尝试模拟一个函数,不确定在这里我在做什么错。我有这个功能“ getGroups”
getGroups:
export const getGroups = async () => {
try {
const groupApiUrl = getDashboardPath(GROUPS_TAB_INDEX);
const data = await fetch(groupApiUrl, { cache: 'force-cache' });
const userData = await data.json();
return userData;
} catch (error) {
throw Error(error);
}
};
___ mocks ___ / getGroups.js:
export default async () => {
return {
groups: [
{ id: 1, name: 'Data1' },
{ id: 2, name: 'Data2' }
]
};
};
getGroups.test.js:
jest.mock('./getGroups.js');
// eslint-disable-next-line import/first
import { getGroups } from './getGroups';
const fakeRespose = {
groups: [
{ id: 1, name: 'Data1' },
{ id: 2, name: 'Data2' }
]
};
describe('getGroups', () => {
it('returns data', async () => {
const data = await getGroups();
console.log('DATA', data); <---- UNDEFINED?
expect(data).toBeDefined();
expect(data).toMatchObject(fakeRespose);
});
it('handles error', async () => {
// const data = await getGroups();
await getGroups().toThrow('Failed');
});
});
0
投票
投票
从Jest Docs,这是一个模拟的例子。
jest.mock('../moduleName', () => {
return jest.fn(() => 42);
});
// This runs the function specified as second argument to `jest.mock`.
const moduleName = require('../moduleName');
moduleName(); // Will return '42';
在您的情况下data
未定义,因为您实际上并未嘲笑getGroups
的实现。因此,您仍在运行原始的getGroups
函数-失败并显示错误。
示例参考:https://jestjs.io/docs/en/jest-object#jestmockmodulename-factory-options
但是,在您的简单情况下,您也可以用jest.spyOn
或jest.fn()
间谍解决此问题。这是您要实现的两种解决方案。您可以查看代码并在此处运行它:https://repl.it/repls/FairUnsungMice