如何测试从外部API提取数据的组件?

时间:2019-10-21 12:22:12

标签: javascript reactjs testing

我正在尝试测试一个从Axios提取数据的组件,并且一直给我一个错误,即提取的数据未定义。我正在使用玩笑和反应测试库,还嘲笑Axios。测试结果显示Axios模拟已被调用,但它始终返回未定义的结果。这是代码:

const lyricData = {
  message: {
    body: {
      lyrics: {
        lyric:
          "Do you love the rain, does it make you dance",
       lyrics_copyright:
          'Lyrics powered by www.musixmatch.com. This Lyrics is NOT for Commercial use and only 30% of the lyrics are returned.',

      }
    },
   }
};

afterEach(cleanup);
const props = {
  tracks: [
    {
      track: {
        track_id: 181987382,
        artist_name: 'sama',
        tracks: 'Hold my Liquor'
      }
    }
  ]
};

it('loads and displays lyric', async () => {
  axiosMock.get.mockResolvedValue({ data: lyricData });

  const url = `https://cors-anywhere.herokuapp.com/https://api.musixmatch.com/ws/1.1/track.lyrics.get?format=json&callback=callback&track_id=181987382&apikey=${process.env.REACT_APP_API_KEY}`;
  const { getByTestId, getByTitle } = render(<Lyrics {...props} />);

  const loading = getByTestId('loading');
  const title = getByTitle('Next Lyric');

  expect(loading).toBeInTheDocument();
  expect(title).toBeInTheDocument();

  const resolvedValue = await waitForElement(() => getByTestId('lyrics'));

  expect(resolvedValue).toBeInTheDocument();

  expect(axiosMock.get).toHaveBeenCalledTimes(1);
  expect(axiosMock.get).toHaveBeenCalledWith(url);
});

在下面的组件中一直说lyricData.lyric是未定义的

const [lyrics, setLyrics] = useState();
  const [copyright, setCopyRight] = useState();
  const [count, setCount] = useState(0);

  const trackName = tracks[count];
  const trackId = trackIds[count];

  const classes = useStyles();
  const rand = randomNumber(trackIds.length);

  useEffect(() => {
    const getLyrics = async (id) => {
      const lyricData = await generateLyric(id);
      setLyrics(lyricData.lyric);
      setCopyRight(lyricData.lyrics_copyright);
    };
    if (trackId) getLyrics(trackId);
  }, [trackId, trackIds]);

这是生成歌词函数:

export const generateLyric = async (trackId) => {
  const sanitizeLyrics = (lyric) => {
    const noNewLines = lyric.replace('/\n/g', ' ');
    const truncateLyric = noNewLines
      .split(' ')
      .splice(5, 55)
      .join(' ');
    return truncateLyric;
  };
  const url = `https://api.musixmatch.com/ws/1.1/track.lyrics.get?format=json&callback=callback&track_id=${trackId}&apikey=${process.env.REACT_APP_API_KEY}`;
  try {
    const { result } = await getApiData(url);
    const { lyrics_body, lyrics_copyright } = result.message.body.lyrics;
    const lyric = sanitizeLyrics(lyrics_body);
    return { lyric, lyrics_copyright };
  } catch (error) {
    console.error(error);
  }
};

0 个答案:

没有答案