我如何在React axios的此功能中进行笑话测试?

时间:2019-03-19 17:44:33

标签: reactjs jestjs axios moxios

我在React中创建了一个服务,我需要测试服务的这一部分,我使用axios和Jest来做到这一点。 我在React中有下一个代码:

import axios from 'axios';
import Endpoints from './endpoints';
const baseUrl = Endpoints.getBackendEndpoint();

export const validateName =  (nameObject, callback) => {
 axios.post(`${baseUrl}/validateName`, {...nameObject})
   .then(response =>{ 
      response.data
    })
   .then(data => callback(data));
};

我不需要退还诺言,因为所有工作都由callback()函数完成。

这是我在Jest中拥有的代码:

mport moxios from 'moxios';
import * as service from '../service';
import mockResponses from './service.test.json';
import Endpoints from '../endpoints';


const validateObjName = {
    Id: 1,
    Name: 'Bob',
  }

beforeEach(() => {
const baseUrl = Endpoints.getBackendEndpoint();
  moxios.stubRequest(
    `${baseUrl}/validateName`,
    { ...validateObjName },
    {
      status: 200,
      response: mockResponses.validateForm,
    }
  );
});

afterEach(() => {
  moxios.uninstall();
});

it('validateName()', () => {
   service.validateName(validateObjName, jest.fn());
});

可以,但是仍然需要增加分支机构的覆盖范围。

感谢您的帮助:D

1 个答案:

答案 0 :(得分:0)

要获得代码覆盖率,代码必须在测试运行时运行 ,因此您需要返回MediaPlayer music; //do this in onCreate music = MediaPlayer.create(getApplicationContext(), R.raw.sunnybike2); music.start(); Handler ha = new Handler(); Runnable mFadeRun; Float musicVolumeF = 1.0f; void musicFader(Float desiredVolume) { mFadeRun = new Runnable() { @Override public void run() { // decrement the float value musicVolumeF = musicVolumeF - 0.02f; // so it does not go below 0 if (musicVolumeF < 0) musicVolumeF = 0.0f; // set the volume to the new slightly less float value music.setVolume(musicVolumeF, musicVolumeF); // so it stops if it's at about the desired volume // you can change the 20 to make it go faster or slower if (musicVolumeF > desiredVolume+0.02) ha.postDelayed(mFadeRun,20); } }; // postDelayed re-posts the Runnable after the given milliseconds ha.postDelayed(mFadeRun,20); } ,以便可以在测试中Promise,以便await回调在测试过程中运行

此外,您可以将then简化为:

validateName

在测试中,您需要在import axios from 'axios'; import Endpoints from './endpoints'; const baseUrl = Endpoints.getBackendEndpoint(); export const validateName = (nameObject, callback) => { return axios.post(`${baseUrl}/validateName`, { ...nameObject }) .then(response => callback(response.data)); }; 中安装moxios,并将模拟响应作为第二个参数传递给beforeEach

然后使用moxios.stubRequest测试函数和async返回的await Promise

validateName

那应该给您一个有效的测试并覆盖100%的代码。