class Users {
static all() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => {
if(response) {
return response.json();
}
});
}
}
export default Users;
import React, { Component } from 'react';
import { StyleSheet, View, TextInput } from 'react-native';
import Users from './api/users';
export default class Home extends Component {
componentDidMount() {
Users.all().then((data)=> {
console.warn("check api data", data);
});
}
render() {
return (
<View style={styles.wrapper}>
<TextInput
testID={'username'}
style={{backgroundColor: 'gray', marginBottom: 35}}
placeholder={'Enter User Name'} />
<TextInput
testID={'password'}
style={{backgroundColor: 'gray'}}
placeholder={'Enter Password'} />
</View>
)
}
}
const styles = StyleSheet.create({
wrapper: {
flex:1,
justifyContent: 'center'
},
})
import Users from '../app/api/users';
it('Api test', async function() {
global.fetch = jest.fn().mockImplementation(()=>{
var p = new Promise((resolve, reject) => {
resolve({
json:function() {
return {Id:1}
}
})
})
return p;
})
const response = await Users.all();
// console.log(response);
expect(response.Id).toBe(1);
})
此時的 Users.all() 並非真的跑去call fb那串API,因為 global.fetch... 所以被判定使用模擬函數(mock function )
fetch is not defined的原因:
在測試區域(test area)內,我們無法通過 test 偵測它到底是什麼東西,所以我們使用 isomorphic-fetch
$ npm install --save isomorphic-fetch es6-promise
$ npm install
3) 在 HomeMockApi-test.js內import isomorphic-fetch
執行test case,結果是失敗,但可以看到成功印出從API內獲取的內容,如下圖
import Users from '../app/api/users';
import 'isomorphic-fetch';
it('Api test', async function() {
const response = await Users.all();
console.log(response);
expect(response.Id).toBe(1);
})
import Users from '../app/api/users';
import 'isomorphic-fetch';
it('Api test', async function() {
const response = await Users.all();
// console.log(response);
expect(response.movies[3].title).toEqual('Inception');
})