标签: ts-jest

即使在设置computeStyleSupportsPseudoElements:true之后,@testing-library/dom window.getCompulatedStyle“未实现”错误

我正在使用 jest 来测试实现 React Embla 轮播的自定义模块。

我收到与 jsdom 缺少实现相关的错误window.getComputedStyle(elt, pseudoElt)

Error: Not implemented: window.computedStyle(elt, pseudoElt)
Run Code Online (Sandbox Code Playgroud)

经过一番搜索后,我发现 jsdom 不支持第二个参数,并且 jsdom 的优秀人员可以@testing-library选择对此做一些事情。

参考

https://testing-library.com/docs/dom-testing-library/api-configuration#compulatedstylesupportspseudoelements

笑话设置.js:

import { configure } from '@testing-library/dom';
configure({
  computedStyleSupportsPseudoElements: true
})
import '@testing-library/jest-dom';
Run Code Online (Sandbox Code Playgroud)

但不幸的是,这似乎并不能解决我的错误。我知道正在应用配置,因为我设置了一些其他配置选项,这些选项破坏了我的所有测试。

我是否没有正确应用某些内容,或者是否有其他可能的解决方法?我在测试中不需要轮播的完整功能,我只想确保传递给视图的数据能够正确呈现。

javascript jsdom reactjs jestjs ts-jest

4
推荐指数
1
解决办法
7477
查看次数

如何使用 typescript、react 和 jest 进行手动模拟?

我试图使用 jest 来模拟 React 组件使用的钩子的返回值,但我无法让它工作。考虑价格标签部分。它所做的只是渲染从挂钩返回的价格usePrice

usePrice.ts

export default function usePrice() {
  return 1337;
}
Run Code Online (Sandbox Code Playgroud)

PriceTag.tsx

import React from 'react';
import usePrice from './usePrice';

export default function PriceTag() {
  const price = usePrice();

  return <p>Price: {price}</p>
}
Run Code Online (Sandbox Code Playgroud)

在测试中,我断言显示了正确的价格。由于我想为此组件创建多个测试,因此setPrice使用帮助器为每个测试设置下一个返回值。

__mocks__/usePrice.ts

let price = 58008;

export function setPrice(newPrice) {
  price = newPrice;
}

export default function usePrice() {
  return price;
}
Run Code Online (Sandbox Code Playgroud)

PriceTag.test.tsx

import { render } from '@testing-library/react';
import React from 'react';
import PriceTag …
Run Code Online (Sandbox Code Playgroud)

mocking typescript reactjs react-tsx ts-jest

4
推荐指数
1
解决办法
3907
查看次数

如何允许 screen.getByText() 在笑话+反应测试中失败

我有一个测试用例。该项目正在使用@testing-library/react

it('renders content if loading is false', async () => {
    await waitFor(() => {
      render(<Loader loading={false}><span>foo</span></Loader>);
    });
    const loaderElementText = screen.getByText('Loading');
    expect(loaderElementText).not.toBeInTheDocument();
    const contentText = screen.getByText('foo');
    expect(contentText).toBeInTheDocument();
  });
Run Code Online (Sandbox Code Playgroud)

它不允许我运行expect(loaderElementText).not.toBeInTheDocument();带有以下错误的行:

TestingLibraryElementError: Unable to find an element with the text: Loading. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
Run Code Online (Sandbox Code Playgroud)

反向测试用例按loading={true}预期工作。

我已经无计可施了。查询文档中的元素并期望找不到该元素的语法是什么?

javascript testing automated-tests reactjs ts-jest

4
推荐指数
1
解决办法
4707
查看次数

如何模拟包含正斜杠的模块?

模拟标准 npm 项目非常简单。在node_modules文件夹旁边创建一个__mocks__文件夹,然后将包的名称作为文件,并在其中写入mock内容。

例子:/__mocks__/axios.ts

我陷入困境的是有一个 npm 包导入,如下所示:@auth0/auth0-react

我怎样才能模拟这个文件的内容?我尝试创建一个名为@auth0/auth0-react.tsx但 jest 似乎没有拾取模拟文件的文件。当我导入import { Auth0Provider } from '@auth0/auth0-react';and时console.log(Auth0Provider),我得到的只是标准Jest.fn()属性。

这是模拟文件的内容

/* eslint-disable import/prefer-default-export */
export const Auth0Provider = (component: JSX.Element): JSX.Element => component;
Run Code Online (Sandbox Code Playgroud)

由于我没有使用jest.fn()这一种方法,因此我希望console.log(Auth0Provider)表明它包含一个函数。

在我的测试代码中,我在jest.mock('@auth0/auth0-react')测试之前。有任何想法吗?

mocking typescript jestjs ts-jest

4
推荐指数
1
解决办法
1011
查看次数

创建 React App Rewired 应用程序忽略 jest.config.js

我有一个使用“创建反应应用程序重新连线”创建的反应应用程序。我已经安装了 ts-jest 并且希望能够自定义 Jest。我阅读了 ts-jest 的文档并npx ts-jest config:init在项目的根级别执行以创建初始配置文件。为了测试 jest 是否确实使用该配置文件,我console.log(window);在示例测试文件中编写了以下行,并修改了配置,将其testEnvironment设置为“node”。

我预计测试会因window未定义而失败,但我正在恢复窗口对象。我尝试将文件重命名为jest.config.ts,但得到了相同的结果。

我对所有文件进行了全局搜索,以查看是否有另一个配置文件覆盖了我的配置,但没有找到。

我究竟做错了什么?我知道 jest 是通过 create-react-app (CRA) 预先打包的。我想 create-react-app-rewired 只会包含 CRA 之上的一些包装器,那么它从哪里获取配置呢?

configuration config create-react-app ts-jest

4
推荐指数
1
解决办法
1450
查看次数

开玩笑没有找到别名路径

我最近创建了一个别名路径来导入我的组件,这样我就可以避免像这样导入组件../../../../componentFolder,而是这样做@src/componentFolder。\n我的问题是我的单元测试停止工作,因为它找不到导入组件的路径。\n我的文件结构如下。

\n
webpack.config.js\ntsconfig.json\nclient\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 jest.config.js\n|   tsconfig.json\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 src\n\xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 AgentsView\n\xe2\x94\x82   |   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 AgentsView.tsx\n\xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 OtherComponent\n\xe2\x94\x82   |   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 OtherComponent.tsx\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 test\n\xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 AgentsView\n\xe2\x94\x82   |   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 AgentsView.spec.tsx\n\xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 OtherComponent\n\xe2\x94\x82   |   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 OtherComponent.spec.tsx\n\xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 tsconfig.json\n
Run Code Online (Sandbox Code Playgroud)\n

我的webpack.config.js是这样的

\n
module.exports = {\n\nresolve: {\n    extensions: ['.mjs', '.js', '.ts', '.tsx', '.scss'],\n    alias: {\n        '@src': path.resolve(__dirname, './client/src/'),\n        '@components': path.resolve(__dirname, './client/src/components/'),\n    }\n}, ...etc\n
Run Code Online (Sandbox Code Playgroud)\n

我的tsconfig.json我添加了 2 个paths

\n
"compilerOptions": {\n    "jsx": "react",\n    "sourceMap": true,\n    "moduleResolution": "node",\n    "baseUrl": "client",\n    "paths": {\n        "@src/*": …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs webpack jestjs ts-jest

4
推荐指数
1
解决办法
8054
查看次数

如何使用当前的 ts-jest 获取覆盖图?

Jest、Typescript、ts-jest 类似:覆盖范围略有不正确- 但是那里的答案适用于mapCoverage存在该选项的旧版本的 jest。

mapCoverage现在已被删除,我的印象是 ts-jest 现在应该提供开箱即用的覆盖率报告。

我已按照ts-jest 文档安装并运行 ts-jest:

npm install --save-dev jest typescript ts-jest @types/jest
npx ts-jest config:init
npx jest --coverage --coverageDirectory='coverage'
open coverage/lcov-report/index.ts.html
Run Code Online (Sandbox Code Playgroud)

但是我可以看到覆盖率报告生成了不正确的地图:

在此输入图像描述

如何使用当前的 ts-jest 获取覆盖图?

我尝试添加collectCoverage: true到我的jest.config.js,但没有改变输出。

typescript jestjs ts-jest

4
推荐指数
1
解决办法
1440
查看次数

jest.mock 不适用于 Javascript 测试和 Typescript 模块

我的模拟utilFunction没有被使用,并且向工厂函数添加日志记录表明它从未被调用。我已经尝试过搜索 jest.mock 不使用相对路径,并且 jest.mock 没有被 Typescript 调用,认为它可能与 JS 测试和 TS 源代码的混合或源中使用的不同模块路径有关与测试代码。

正在测试的代码:

// src/foo/fooModule.ts
import { utilFunction } from '../util'

export const foo = () => {
  return utilFunction()
}
Run Code Online (Sandbox Code Playgroud)

测试代码:

// test/fooModule.test.js
const { foo } = require('../src/foo/fooModule')

jest.mock('../src/util', () => {
  return { utilFunction: () => 'mocked' };
});

describe('fooModule tests', () => ...)
Run Code Online (Sandbox Code Playgroud)

javascript typescript jestjs ts-jest

4
推荐指数
1
解决办法
3163
查看次数

react-native, jest, ts-jest: ReferenceError: React 未定义

我已经努力了几天,以便使用 expo + typescript + jest + ts-jest 为简单的 react-native 运行测试。我已经 这里问了一个相关的问题这是我的项目的设置:

  1. 配置文件
    {
      "compilerOptions": {
        "noEmit": true,
        "lib": ["dom", "esnext"],
        "jsx": "react-native",
        "moduleResolution": "node",
        "allowSyntheticDefaultImports": true,
        "skipLibCheck": true
      }
    }
Run Code Online (Sandbox Code Playgroud)
  1. babel.config.json
module.exports = function(api) {
  api.cache(true);
  return {
    presets: ["babel-preset-expo"]
  };
};
Run Code Online (Sandbox Code Playgroud)
  1. jest.config.js(见官方github设置 react-native + ts-jest
const { defaults: tsjPreset } = require("ts-jest/presets");
module.exports = {
  ...tsjPreset,
  preset: "react-native",
  transform: {
    ...tsjPreset.transform,
    "\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
  },
  globals: {
    "ts-jest": {
      babelConfig: true
    }
  },
  cacheDirectory: ".jest/cache"
}; …
Run Code Online (Sandbox Code Playgroud)

jestjs react-native expo ts-jest

3
推荐指数
1
解决办法
1066
查看次数

如何检查是否在嵌套的 jest 模拟函数中调用了一个方法

我有一个像下面这样的模拟服务

  const firebaseService = jest.fn(() => ({
    initializeApp: jest.fn(() => { /*do nothing*/}),
  }))
Run Code Online (Sandbox Code Playgroud)

在我的测试中,我想要expectifinitializeApp已经被调用。我该如何检查?

it('should be called', () => {
   expect(???).toHaveBeenCalledTimes(1);
});
Run Code Online (Sandbox Code Playgroud)

更新:真实场景

  const collection = jest.fn(() => {
    return {
      doc: jest.fn(() => {
        return {
          collection: collection,
          update: jest.fn(() => Promise.resolve(true)),
          onSnapshot: jest.fn(() => Promise.resolve(true)),
          get: jest.fn(() => Promise.resolve(true))
        }
      }),
      where: jest.fn(() => {
        return {
          get: jest.fn(() => Promise.resolve(true)),
          onSnapshot: jest.fn(() => Promise.resolve(true)),
          limit: jest.fn(() => {
            return {
              onSnapshot: jest.fn(() …
Run Code Online (Sandbox Code Playgroud)

javascript jestjs ts-jest

3
推荐指数
1
解决办法
9635
查看次数