今回はAPIのtestをします。
APIをたたく
axiosを使います。
testを書く
Api.spec.js
import * as axios from 'axios';
describe('api-test', () => {
it('axios mock', async () => {
jest.mock('axios', () => ({
get: (url, body) => {
return new Promise(resolve => {
resolve({url, body}).catch(err => {
throw new Error(err)
})
})
}
}))
const SampleFunction= async () => {
const res = await axios.get('https://samplefunction_api.com/api/posts/all')
console.log(res)
return res
}
expect(SampleFunction)
})
});
describe()
describe()
引数にtest名を入れることでtestを宣言します。
it()
it()
引数にテストする内容記載できます。
jest.mock()
公式から引用
すべてのモック関数には、この特別な .mock プロパティがあり、モック関数呼び出し時のデータと、関数の返り値が記録されています。 .mock プロパティには、各呼び出し時の thisの値も記録されているため、this の値のチェックも可能です。
jest.mock()
引数の中でaxios
を指定することで使用できるようになる
mock作成
get: (url, body) => {
return new Promise(resolve => {
resolve({url, body}).catch(err => {
throw new Error(err)
})
})
}
上の部分がaxiosのmock作成箇所
getメソッドを利用しPromiseで値を返すように記述している
axiosでApiを叩く
const SampleFunction= async () => {
const res = await axios.get('https://samplefunction_api.com/api/posts/all')
console.log(res)
return res
}
expect(SampleFunction)
上の箇所でapiを叩いてPromiseでレスポンスを返すように設定している
expect()
引数にtest対象を指定する
動作確認
jest test
url, body
がこんな感じで返ってきます
一応今回test書いたgithub貼っておきます。
https://github.com/taichi0514/headlesscms-view