反应本机开玩笑的模拟api调用自定义模块

时间:2020-04-29 14:53:27

标签: react-native jestjs expo

我是Jest的新手,刚刚学习了React Native Expo。我有一个处理对服务器的api调用的服务。我想通过模拟来测试该服务。我完全不知道为什么它不起作用。关于嘲笑的Jest文档对我来说很模糊。

我不明白为什么我的原始方法没有被模拟。

我的目录如下:

services
├── __tests__
|   └──goalService.test.js
|
├── __mocks__
│   └── goalService.tsx
|
└── goalService.tsx

服务根目录中的goalService.tsx具有返回承诺的方法。

每个文件中的代码:

模拟文件夹中的goalService.tsx

// __mocks__/goalService.tsx
class GoalService {

    fakeGoals = [
        {
            "id": 1,
            "name": "Test",
            "description": "test test test",
            "user_id": 2,
            "createdAt": "2020-04-13T11:03:47.231Z",
            "updatedAt": "2020-04-13T13:28:58.305Z"
        }
    ];

    GetGoals = (userID) => {
        return new Promise((resolve, reject) => {
            resolve(this.fakeGoals);
        });
    }

    AddGoal = (newGoal) => {
        this.fakeGoals.push(newGoal);

        return new Promise((resolve, reject) => {
            resolve(this.fakeGoals);
        })
    }
}

tests文件夹中的goalService.js

// __tests__/goalService.js
import GoalService from './../goalService';

jest.mock('./../goalService');

it('Fetches goals data', done => {
    return GoalService.GetGoals(2).then(data => {
        expect(data.length).toBeGreaterThan(0);
        done();
    });
});

goalService.tsx

// goalService.tsx
class GoalService {

    url = 'xxx';

    GetGoals = (userID) => {
        return fetch(this.url + 'goal/user/' + userID)
            .then((response) => { 
                return response.json();
            }).then((data) => {
              return data.reverse();
            })
            .catch((error) => {
              console.error('Error:', error);
            });
    }

    AddGoal = (newGoal) => {
        return fetch(this.url + 'goal', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(newGoal)
        }).then((response) => response.json())
            .then((data) => {
                console.log('Success:', data);
                return data;
            })
            .catch((error) => {
                console.error('Error:', error);
                return false;
            });
    }
}
...

const goalService = new GoalService();
export default goalService;

测试给出以下错误:

TypeError: _goalService.default.GetGoals is
not a function

我究竟如何测试GetGoals和AddGoals?

我真的被困在这里,请帮助我。

谢谢!

0 个答案:

没有答案