Create React App 无法正确模拟 __mocks__ 目录中的模块 [英] Create React App doesn't properly mock modules from __mocks__ directory

查看:16
本文介绍了Create React App 无法正确模拟 __mocks__ 目录中的模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自 __mocks__ 目录中的 Jest 和模拟的工作示例:

通过简单的 Jest 设置

//package.json{名称":一个",版本":1.0.0",主要":index.js",脚本":{测试":开玩笑";},...开发依赖":{开玩笑":^26.6.3"},依赖关系":{@octokit/rest":^18.0.12"}}

然后 /index.js :

const { Octokit } = require("@octokit/rest");const octokit = new Octokit();module.exports.foo = function() {return octokit.repos.listForOrg({ org: "octokit", type: "public" })}

及其测试(/index.test.js):

const { foo } = require("./index.js");test(foo 应该是真的", async() => {期望(等待 foo()).toEqual([1,2]);});

和模拟(/__mocks__/@octokit/rest/index.js):

module.exports.Octokit = jest.fn().mockImplementation( () => ({回购:{listForOrg: jest.fn().mockResolvedValue([1,2])}}) );

效果很好,测试通过.

使用创建 React 应用程序

然而,对 Create React App 做同样的事情似乎给了我一个奇怪的结果:

//package.json{名称":b",版本":0.1.0",依赖关系":{@octokit/rest":^18.0.12",@testing-library/jest-dom":^5.11.4",@testing-library/react":^11.1.0",@testing-library/user-event":^12.1.10",反应":^ 17.0.1",react-dom":^17.0.1",反应脚本":4.0.1",网络生活":^0.2.4"},脚本":{开始":反应脚本开始",构建":反应脚本构建",测试":反应脚本测试",弹出":反应脚本弹出";},...}

然后/src/foo.js:

从@octokit/rest"导入{ Octokit };const octokit = new Octokit();module.exports.foo = function() {return octokit.repos.listForOrg({ org: "octokit", type: "public" })}

及其测试(/src/foo.test.js):

const { foo} = require("./foo.js");test(foo 应该是真的", async() => {期望(等待 foo()).toEqual([1,2]);});

和完全相同的模拟(在 /src/__mocks__/@octokit/rest/index.js 下):

export const Octokit = jest.fn().mockImplementation( () => ({回购:{listForOrg: jest.fn().mockResolvedValue([1,2])}}) );

这会使测试失败:

 失败 src/foo.test.js✕ foo 应该是真的(2 毫秒)● foo 应该是真的expect(received).toEqual(expected)//深度相等预期:[1, 2]收到:未定义2 |3 |test(foo 应该是真的", async() => {>4 |期望(等待 foo()).toEqual([1,2]);|^5 |});6 |7 |在对象<匿名>(src/foo.test.js:4:25)

在阅读了很多之后,我似乎无法让 __mocks__ 在 Create React App 中工作.有什么问题?

解决方案

问题在于 CRA 的默认 Jest 设置会自动重置模拟,从而删除您设置的 mockResolvedValue.


解决这个问题的一种方法,它也使您可以更好地控制在不同的测试中使用不同的值(例如测试错误处理)并断言它被称为with,是公开模拟来自模块的功能:

export const mockListForOrg = jest.fn();export const Octokit = jest.fn().mockImplementation(() => ({回购:{listForOrg:mockListForOrg,},}));

然后你在测试中配置你想要的值,之后 Jest 会重置它:

import { mockListForOrg } from "@octokit/rest";从./foo"导入 { foo };test(foo 应该是真的", async() => {mockListForOrg.mockResolvedValueOnce([1, 2]);期望(等待 foo()).toEqual([1, 2]);});


另一种选择是将以下内容添加到您的 package.json 中以覆盖该配置,根据 这个问题:

{...开玩笑":{resetMocks":假}}

不过,这可能会导致在测试之间保留模拟状态(收到的调用)的问题,因此您需要确保它们被清除和/或重置某处.>


请注意,您通常不应该嘲笑您不拥有的东西 - 如果 @octokit/rest 的接口发生变化,您的测试将继续通过,但您的代码将不会通过不工作.为了避免这个问题,我会推荐以下任一或两个:

  • 将断言移动到传输层,例如使用MSW 检查是否做出了正确的请求;或
  • 编写一个包装 @octokit/rest 的简单外观,将您的代码与您不拥有的接口分离,并模拟它;

以及更高级别(端到端)的测试,以确保一切都与真正的 GitHub API 一起正常工作.

事实上,删除模拟并编写这样一个使用 MSW 的测试:

import { rest } from "msw";从msw/node"导入 { setupServer };从./foo"导入 { foo };const server = setupServer(rest.get(https://api.github.com/orgs/octokit/repos", (req, res, ctx) => {返回 res(ctx.status(200), ctx.json([1, 2]));}));beforeAll(() => server.listen());afterAll(() => server.close());test(foo 应该是真的", async() => {期望(等待 foo()).toEqual([1, 2]);});

表明当前关于 octokit.repos.listForOrg 将返回什么的假设是不准确的,因为这个测试失败了:

 ● foo 应该是真的expect(received).toEqual(expected)//深度相等预期:[1, 2]收到:{数据":[1, 2],标题":{内容类型":应用程序/json",x-power-by":msw"},";状态":200,url":https://api.github.com/orgs/octokit/repos?type=public"}13 |14 |test(foo 应该是真的", async() => {>15 |期望(等待 foo()).toEqual([1, 2]);|^16 |});17 |在对象<匿名>(src/foo.test.js:15:25)

您的实现实际上应该看起来更像:

导出异步函数 foo() {const { data } = await octokit.repos.listForOrg({ org: "octokit", type: "public" });返回数据;}

或:

导出函数 foo() {return octokit.repos.listForOrg({ org: "octokit", type: "public" }).then(({ data }) => data);}

I have a working example with Jest and mocks from __mocks__ directory that works :

With simple Jest setup

// package.json
{
  "name": "a",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  ...
  "devDependencies": {
    "jest": "^26.6.3"
  },
  "dependencies": {
    "@octokit/rest": "^18.0.12"
  }
}

And then /index.js :

const { Octokit } = require("@octokit/rest");

const octokit = new Octokit();

module.exports.foo = function() {
  return octokit.repos.listForOrg({ org: "octokit", type: "public" })
}

with its test (/index.test.js):

const { foo } = require("./index.js");

test("foo should be true", async () => {
    expect(await foo()).toEqual([1,2]);
});

and the mock (/__mocks__/@octokit/rest/index.js):

module.exports.Octokit = jest.fn().mockImplementation( () => ({
    repos: {
        listForOrg: jest.fn().mockResolvedValue([1,2])
    }
}) );

This works quite well and tests pass.

With Create React App

However doing the same with Create React App seems to be giving me a weird result:

// package.json
{
  "name": "b",
  "version": "0.1.0",
  "dependencies": {
    "@octokit/rest": "^18.0.12",
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "4.0.1",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  ...
}

And then /src/foo.js:

import { Octokit } from "@octokit/rest";

const octokit = new Octokit();

module.exports.foo = function() {
  return octokit.repos.listForOrg({ org: "octokit", type: "public" })
}

with its test (/src/foo.test.js):

const { foo} = require("./foo.js");

test("foo should be true", async () => {
    expect(await foo()).toEqual([1,2]);
});

and the very same mock (under /src/__mocks__/@octokit/rest/index.js):

export const Octokit = jest.fn().mockImplementation( () => ({
    repos: {
        listForOrg: jest.fn().mockResolvedValue([1,2])
    }
}) );

This makes the test fail:

 FAIL  src/foo.test.js
  ✕ foo should be true (2 ms)

  ● foo should be true

    expect(received).toEqual(expected) // deep equality

    Expected: [1, 2]
    Received: undefined

      2 |
      3 | test("foo should be true", async () => {
    > 4 |     expect(await foo()).toEqual([1,2]);
        |                         ^
      5 | });
      6 |
      7 |

      at Object.<anonymous> (src/foo.test.js:4:25)

After reading a lot it seems that I can't make __mocks__ work inside Create React App. What's the problem?

解决方案

The problem is that CRA's default Jest setup automatically resets the mocks, which removes the mockResolvedValue you set.


One way to solve this, which also gives you more control to have different values in different tests (e.g. to test error handling) and assert on what it was called with, is to expose the mock function from the module too:

export const mockListForOrg = jest.fn();

export const Octokit = jest.fn().mockImplementation(() => ({
    repos: {
        listForOrg: mockListForOrg,
    },
}));

Then you configure the value you want in the test, after Jest would have reset it:

import { mockListForOrg } from "@octokit/rest";

import { foo } from "./foo";

test("foo should be true", async () => {
    mockListForOrg.mockResolvedValueOnce([1, 2]);

    expect(await foo()).toEqual([1, 2]);
});


Another option is to add the following into your package.json to override that configuration, per this issue:

{
  ...
  "jest": {
    "resetMocks": false
  }
}

This could lead to issues with mock state (calls received) being retained between tests, though, so you'll need to make sure they're getting cleared and/or reset somewhere.


Note that you generally shouldn't mock what you don't own, though - if the interface to @octokit/rest changes your tests will continue to pass but your code won't work. To avoid this issue, I would recommend either or both of:

  • Moving the assertions to the transport layer, using e.g. MSW to check that the right request gets made; or
  • Writing a simple facade that wraps @octokit/rest, decoupling your code from the interface you don't own, and mocking that;

along with higher-level (end-to-end) tests to make sure everything works correctly with the real GitHub API.

In fact, deleting the mocks and writing such a test using MSW:

import { rest } from "msw";
import { setupServer } from "msw/node";

import { foo }  from "./foo";

const server = setupServer(rest.get("https://api.github.com/orgs/octokit/repos", (req, res, ctx) => {
    return res(ctx.status(200), ctx.json([1, 2]));
}));

beforeAll(() => server.listen());

afterAll(() => server.close());

test("foo should be true", async () => {
    expect(await foo()).toEqual([1, 2]);
});

exposes that the current assumption about what octokit.repos.listForOrg would return is inaccurate, because this test fails:

  ● foo should be true

    expect(received).toEqual(expected) // deep equality

    Expected: [1, 2]
    Received: {"data": [1, 2], "headers": {"content-type": "application/json", "x-powered-by": "msw"}, "status": 200, "url": "https://api.github.com/orgs/octokit/repos?type=public"}

      13 | 
      14 | test("foo should be true", async () => {
    > 15 |     expect(await foo()).toEqual([1, 2]);
         |                         ^
      16 | });
      17 | 

      at Object.<anonymous> (src/foo.test.js:15:25)

Your implementation should actually look something more like:

export async function foo() {
  const { data } = await octokit.repos.listForOrg({ org: "octokit", type: "public" });
  return data;
}

or:

export function foo() {
  return octokit.repos.listForOrg({ org: "octokit", type: "public" }).then(({ data }) => data);
}

这篇关于Create React App 无法正确模拟 __mocks__ 目录中的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆