LoginSignup
0
1

More than 3 years have passed since last update.

Typescript Jestでaxiosをモック化する

Posted at

概要

実現したかったのは主に2つ

  • TypeScript x Jestでaxiosをモック化する方法
  • ローカルに置いたJSONファイルを読み込んでAPIレスポンスとして扱う方法

ライブラリバージョン

package.jsonより

  • typescript: 4.1.3
  • jest: 26.6.0
  • axios: 0.21.1

実装

data.json
{
  "name": "Taro",
  "age": 20
}
Person.ts
export class Person {
    name: string;
    age: number
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
}
テスト対象のコード
import axios from "axios";
import { Person } from "./Person";

export class PersonConsumer {

    async get(): Promise<Person> {
        return (await axios.get<Person>('https://hoge.com')).data;
    }
}
テストコード
import axios from "axios";
import data from "../data/data.json";
import { PersonConsumer } from "./PersonConsumer";
jest.mock('axios');

describe('PersonConsumer', () => {

    it('return person from api', async () => {
        const mockedAxios = axios as jest.Mocked<typeof axios>
        mockedAxios.get.mockResolvedValue({data: data});

        const target = new PersonConsumer();
        const actual = await target.get();
        expect(actual.name).toBe('Taro');
        expect(actual.age).toBe(20);
    });

});
0
1
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
0
1