使用模拟功能测试React存储

时间:2019-11-07 21:44:04

标签: reactjs unit-testing jestjs

我通常是新来的反应者和发展者。我想对store.dispatch动作以及是否返回相应的typepayload进行单元测试。我当前的代码结构在返回预期的typepayload之前,要执行一个底层函数。

示例:

export function requestForSomething(number){
  store.dispatch(getData(number));
}
export const getData = number => {
  const productDetails = someFunction(number);
  return { 
    type: GET_DATA,
    productDetails,
  };
}

问题是,如何与Jest一起对上述store.dispatch进行单元测试?是否需要模拟还是可以模拟someFunction(number)以及如何进行模拟。

非常感谢您。

1 个答案:

答案 0 :(得分:1)

这是一个单元测试解决方案,您可以使用jest.spyOn(object, methodName, accessType?)进行此操作。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseStatusCodePagesWithReExecute("/error/{0}"); app.UseExceptionHandler("/error/500"); app.Use(async (context, next) => { await next(); var code = context.Response.StatusCode; var newPath = new PathString("/error/"+code); var originalPath = context.Request.Path; var originalQueryString = context.Request.QueryString; context.Features.Set<IStatusCodeReExecuteFeature>(new StatusCodeReExecuteFeature() { OriginalPathBase = context.Request.PathBase.Value, OriginalPath = originalPath.Value, OriginalQueryString = originalQueryString.HasValue ? originalQueryString.Value : null, }); // An endpoint may have already been set. Since we're going to re-invoke the middleware pipeline we need to reset // the endpoint and route values to ensure things are re-calculated. context.SetEndpoint(endpoint: null); var routeValuesFeature = context.Features.Get<IRouteValuesFeature>(); routeValuesFeature?.RouteValues?.Clear(); context.Request.Path = newPath; try { await next(); } finally { context.Request.QueryString = originalQueryString; context.Request.Path = originalPath; context.Features.Set<IStatusCodeReExecuteFeature>(null); } }); app.UseHttpsRedirection(); app.UseStaticFiles(); //... }

public class ErrorController : Controller
{
    // GET: /<controller>/
    public IActionResult InternalServerError()
    {
        return View();
    }
    [Route("error/404")]
    public IActionResult StatusCode404()
    {
       //redirect to the StatusCode404.cshtml
        return View();
    }
    [Route("error/400")]
    public IActionResult StatusCode400()
    {
        return View();
    }
}

index.ts

import { createStore } from 'redux';

function reducer(state = {}) {
  return state;
}

export const store = createStore(reducer);

export const GET_DATA = 'GET_DATA';

export function requestForSomething(number) {
  store.dispatch(getData(number));
}

export const getData = number => {
  const productDetails = someFunction(number);
  return {
    type: GET_DATA,
    productDetails
  };
};

export const someFunction = number => {
  return number;
};

覆盖率100%的单元测试结果:

index.spec.ts

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58757332