LoginSignup
1
0

More than 3 years have passed since last update.

俺なりのjest

Last updated at Posted at 2019-08-01

今回は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がこんな感じで返ってきます

スクリーンショット 2019-07-31 22.59.41.png スクリーンショット 2019-07-31 22.48.04.png

一応今回test書いたgithub貼っておきます。
https://github.com/taichi0514/headlesscms-view

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0