Jest的spyOn期间的TypeError:无法设置只有getter的#<Object>的属性getRequest

J. *_*ers 14 unit-testing spy reactjs jestjs spyon

我正在用TypeScript编写一个React应用程序.我使用Jest进行单元测试.

我有一个进行API调用的函数:

import { ROUTE_INT_QUESTIONS } from "../../../config/constants/routes";
import { intQuestionSchema } from "../../../config/schemas/intQuestions";
import { getRequest } from "../../utils/serverRequests";

const intQuestionListSchema = [intQuestionSchema];

export const getIntQuestionList = () => getRequest(ROUTE_INT_QUESTIONS, intQuestionListSchema);
Run Code Online (Sandbox Code Playgroud)

getRequest函数如下所示:

import { Schema } from "normalizr";
import { camelizeAndNormalize } from "../../core";

export const getRequest = (fullUrlRoute: string, schema: Schema) =>
  fetch(fullUrlRoute).then(response =>
    response.json().then(json => {
      if (!response.ok) {
        return Promise.reject(json);
      }
      return Promise.resolve(camelizeAndNormalize(json, schema));
    })
  );
Run Code Online (Sandbox Code Playgroud)

我想尝试使用Jest的API函数,如下所示:

import fetch from "jest-fetch-mock";
import { ROUTE_INT_QUESTIONS } from "../../../config/constants/routes";
import {
  normalizedIntQuestionListResponse as expected,
  rawIntQuestionListResponse as response
} from "../../../config/fixtures";
import { intQuestionSchema } from "../../../config/schemas/intQuestions";
import * as serverRequests from "./../../utils/serverRequests";
import { getIntQuestionList } from "./intQuestions";

const intQuestionListSchema = [intQuestionSchema];

describe("getIntQuestionList", () => {
  beforeEach(() => {
    fetch.resetMocks();
  });

  it("should get the int question list", () => {
    const getRequestMock = jest.spyOn(serverRequests, "getRequest");
    fetch.mockResponseOnce(JSON.stringify(response));

    expect.assertions(2);
    return getIntQuestionList().then(res => {
      expect(res).toEqual(expected);
      expect(getRequestMock).toHaveBeenCalledWith(ROUTE_INT_QUESTIONS, intQuestionListSchema);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

问题是该行spyOn抛出以下错误:

  ? getRestaurantList › should get the restaurant list

    TypeError: Cannot set property getRequest of #<Object> which has only a getter

      17 |
      18 |   it("should get the restaurant list", () => {
    > 19 |     const getRequestMock = jest.spyOn(serverRequests, "getRequest");
         |                                 ^
      20 |     fetch.mockResponseOnce(JSON.stringify(response));
      21 |
      22 |     expect.assertions(2);

      at ModuleMockerClass.spyOn (node_modules/jest-mock/build/index.js:706:26)
      at Object.spyOn (src/services/api/IntQuestions/intQuestions.test.ts:19:33)
Run Code Online (Sandbox Code Playgroud)

我google了这个,只发现了关于热重装的帖子.那么在Jest测试期间可能导致什么呢?我怎样才能通过这项测试?

The*_*e F 25

正如评论中所建议的,jest 需要在测试对象上设置一个 setter,而 es6 模块对象没有。jest.mock()允许您通过在导入后模拟所需的模块来解决此问题。

尝试模拟 serverRequests 文件中的导出

import * as serverRequests from './../../utils/serverRequests';
jest.mock('./../../utils/serverRequests', () => ({
    getRequest: jest.fn()
}));

// ...
// ...

it("should get the int question list", () => {
    const getRequestMock = jest.spyOn(serverRequests, "getRequest")
    fetch.mockResponseOnce(JSON.stringify(response));

    expect.assertions(2);
    return getIntQuestionList().then(res => {
        expect(res).toEqual(expected);
          expect(getRequestMock).toHaveBeenCalledWith(ROUTE_INT_QUESTIONS, intQuestionListSchema);
    });
});
Run Code Online (Sandbox Code Playgroud)

这里有一些有用的链接:
https : //jestjs.io/docs/en/es6-class-mocks
https://jestjs.io/docs/en/mock-functions


iar*_*oyo 18

使用ts-jestas 编译器进行测试,如果您以这种方式模拟模块,它将起作用:

import * as serverRequests from "./../../utils/serverRequests";

jest.mock('./../../utils/serverRequests', () => ({
  __esModule: true,
  ...jest.requireActual('./../../utils/serverRequests')
}));

const getRequestMock = jest.spyOn(serverRequests, "getRequest");
Run Code Online (Sandbox Code Playgroud)

开玩笑的官方文档 __esModule


Bri*_*ams 14

这个很有意思.

问题

Babel生成仅为get重新导出的函数定义的属性.

utils/serverRequests/index.ts从其他模块重新导出函数,因此在jest.spyOn用于监视重新导出的函数时会引发错误.


细节

鉴于此代码重新导出以下内容lib:

export * from './lib';
Run Code Online (Sandbox Code Playgroud)

... Babel产生这个:

'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _lib = require('./lib');

Object.keys(_lib).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _lib[key];
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

请注意,属性都是仅定义的get.

尝试jest.spyOn在任何这些属性上使用将生成您看到的错误,因为jest.spyOn尝试用包装原始函数的间谍替换该属性,但如果仅使用该属性定义则不能get.


不是将../../utils/serverRequests(重新导出getRequest)导入到测试中,而是导入getRequest已定义的模块并使用该模块创建间谍.

替代解决方案

utils/serverRequests按照@Volodymyr和@TheF的建议模拟整个模块

  • 有趣的是,`tsc` 和 `ts-jest` 为重新导出的函数生成正常属性,这就是为什么我最初很难重现这个问题。 (3认同)

tvs*_*ent 10

最近我们在我们使用的库中遇到了这样的事情。Babel 只为从库中导出的所有成员提供 getter,所以我们在测试的顶部这样做:

jest.mock('some-library', () => ({
  ...jest.requireActual('some-library')
}));
Run Code Online (Sandbox Code Playgroud)

这解决了这个问题,因为它创建了一个新的、普通的 JS 对象,该对象为库中的每个属性都有一个成员。

  • 除非您同时模拟任何实现,否则上面的操作可以更简单地完成,如 `import * as myModuleRaw from 'myModule'; const myModule = { ...myModuleRaw};`。如果您要对任何方法使用“jest.spyOn()”,则无论如何您都需要该模块作为对象。 (3认同)

Nat*_*hur 6

如果您希望不修改导入,可以通过以下方式解决问题:

import * as lib from './lib'

jest.mock('./lib/subModule')

it('can be mocked', () => {
  jest.spyOn(lib, 'subModuleFunction')
})
Run Code Online (Sandbox Code Playgroud)

您需要jest.mock为您想要监视的任何其他重新导出的函数添加更多行。

  • 我不得不说,额外的 jest.mock 行可以轻松挽救许多生命。谢谢! (2认同)

小智 5

对于遇到此问题的其他人,您可以将 babel 设置为使用“松散”转换,这为我解决了问题。只需将其设置在您的 .babelrc 文件中即可

{
  "presets": [
    ["@babel/preset-env", {
      "loose": true
    }]
  ]
}
Run Code Online (Sandbox Code Playgroud)