这是包含fetch调用的文件,它只发送一些本地存储的json文件.
// eslint-disable-next-line import/prefer-default-export
export const get = () => {
// eslint-disable-next-line no-undef
return fetch('data/posts.json').then((res) => res.json());
};
在我的测试中,我模拟了fetch
方法和Promise.resolve
模拟array.
import { get } from './posts';
const mockData = [
{
"id": "ig-1",
"accountId": "IG",
"accountIcon": "/images/ig-icon.svg",
"accountName": "IG account",
"accountImageInitial": "J",
"imageUrl": "/images/social_logo.png",
"caption": "test",
"timestamp": 1635510651638
},
{
"id": "fb-1",
"accountId": "FB",
"accountIcon": "/images/fb-icon.svg",
"accountName": "FB account",
"accountImageInitial": "J",
"imageUrl": "/images/social_logo.png",
"caption": "test",
"timestamp": 1635510051638
}
];
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve(mockData)
})
);
describe('The posts API controller', () => {
test('get() returns expected default payload', async () => {
const result = await get();
expect(fetch).toHaveBeenCalledTimes(1);
expect(result).toBeTruthy();
});
});
错误
Type错误: Cannot read properties of undefined (reading 'then')
Type错误: Cannot read properties of undefined (reading 'then')
2 | export const get = () => {
3 | // eslint-disable-next-line no-undef
> 4 | return fetch('data/posts.json').then((res) => res.json());
| ^
5 | };
不确定为什么会出现此错误,因为我似乎正确地模拟了fetch?