1

经过多次研究,我从来没有找到一个具体的例子来帮助我理解这一点。

我想要实现的目标:模拟 api 并测试它是否正确渲染。

有人可以给我一个代码示例,看看如何用 jest 来具体测试它,这样我就可以将它应用到我项目中的所有其他函数中,我真的不明白怎么做。

谢谢您的帮助。

来自 api 文件夹的 REAL API

export const searchTrack = search => {
  return fetch(
    `${url}/search/tracks?q=${encodeURIComponent(
      search
    )}&limit=250&media=music`,
    {
      method: "GET",
      headers: {
        Authorization: Cookies.get("token")
      }
    }
  )
    .then(response => {
      return response.json();
    })
    .then(jsonFormat => {
      return jsonFormat.results;
    })
    .catch(() => {
      console.error("fetch for search dont work");
    });
};

调用 addTracksPlaylist.vue 方法

  methods: {
    search() {
      if (this.term !== "") {
        this.results = [];
        this.searching = true;
        apiPlaylist
          .searchTrack(this.term)
          .then(res => {
            if (res.status != 401) {
              this.searching = false;
              this.results = res;
              this.noResults = this.results.length === 0;
            }
          })
          .catch(() => {
            this.$router.push("/login");
          });
      }
    }
  }

我看到每个人都在 api 文件夹中创建了一个 __mocks__ 文件夹,所以我用 api GET return 创建了一个

    {
      wrapperType: "track",
      kind: "song",
      artistId: 461932,
      collectionId: 196480323,
      trackId: 196480329,
      artistName: "Europe",
      collectionName: "The Final Countdown",
      trackName: "The Final Countdown",
      collectionCensoredName: "The Final Countdown",
      trackCensoredName: "The Final Countdown",
      artistViewUrl: "https://itunes.apple.com/us/artist/europe/id461932?uo=4",
      collectionViewUrl:
        "https://itunes.apple.com/us/album/the-final-countdown/id196480323?i=196480329&uo=4",
      trackViewUrl:
        "https://itunes.apple.com/us/album/the-final-countdown/id196480323?i=196480329&uo=4",
      previewUrl:
        "http://a1815.phobos.apple.com/us/r1000/101/Music/70/f0/fd/mzm.hhpjhkpl.aac.p.m4a",
      artworkUrl30:
        "http://a5.mzstatic.com/us/r30/Music/fc/4c/f5/mzi.jpmevzoi.30x30-50.jpg",
      artworkUrl60:
        "http://a4.mzstatic.com/us/r30/Music/fc/4c/f5/mzi.jpmevzoi.60x60-50.jpg",
      artworkUrl100:
        "http://a3.mzstatic.com/us/r30/Music/fc/4c/f5/mzi.jpmevzoi.100x100-75.jpg",
      collectionPrice: 9.99,
      trackPrice: 1.29,
      releaseDate: "1988-09-16T07:00:00Z",
      collectionExplicitness: "notExplicit",
      trackExplicitness: "notExplicit",
      discCount: 1,
      discNumber: 1,
      trackCount: 13,
      trackNumber: 1,
      trackTimeMillis: 310333,
      country: "USA",
      currency: "USD",
      primaryGenreName: "Rock",
      radioStationUrl: "https://itunes.apple.com/station/idra.196480329"
    },
    {}
  ]
};
4

1 回答 1

1

如果您需要通过模拟方法调用的响应来测试您的功能searchTrack,您可以使用 jest 模拟轻松实现此目的。

可以使用简单的jest.fn().

您可以使用以下任一方法提供您自己的实现:

jest.fn(() => { //implementation goes here })

OR

jest.fn().mockImplementation(() => { //implementation goes here })

由于您需要模拟 API 响应,因此您应该有一个返回 Promise 的模拟。

所以这样的事情应该做你的工作:

jest.fn(() => Promise.resolve(mockDataValue))

mockResolvedValueJest 还通过该函数为此提供了简写。

jest.fn().mockResolvedValue(data)

这也是一样的。此外,mockRejectedValue如果您还想测试错误场景,还有该方法。

更多信息可在Jest Mock API 参考中获得

于 2020-04-18T13:47:08.427 回答