小编Muh*_*red的帖子

用 Jest 模拟 axios 会抛出错误“无法读取未定义的属性‘拦截器’”

我在用 Jest 和 react-testing-library 模拟 axios 时遇到了麻烦。我被 axios 拦截器的错误困住了,无法绕过它。

这是我的api.js文件:

import axios from 'axios';

const api = axios.create({
  baseURL: window.apiPath,
  withCredentials: true,
});

api.interceptors.request.use(config => {
  const newConfig = Object.assign({}, config);
  newConfig.headers.Accept = 'application/json';

  return newConfig;
}, error => Promise.reject(error));
Run Code Online (Sandbox Code Playgroud)

在我的组件中调用 api:

const fetchAsync = async endpoint => {
  const result = await api.get(endpoint);
  setSuffixOptions(result.data.data);
};
Run Code Online (Sandbox Code Playgroud)

然后在我的规范文件中:

jest.mock('axios', () => {
  return {
    create: jest.fn(),
    get: jest.fn(),
    interceptors: {
      request: { use: jest.fn(), eject: jest.fn() },
      response: { …
Run Code Online (Sandbox Code Playgroud)

javascript jestjs axios

7
推荐指数
1
解决办法
2910
查看次数

Jest & TypeScript:VS Code 找不到名字

我正在将 Jest 与 TypeScript 一起使用。尽管我的代码可以工作并且我可以构建我的项目,但 Visual Studio Code 会为所有 Jest 方法(describe()test()...)抛出该错误:

Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.ts(2582)
Run Code Online (Sandbox Code Playgroud)

我有srctests分开的目录。我遵循了在 Internet 上找到的配置,但它没有改变任何东西,我错过了什么?到目前为止唯一的方法是将我的tests文件夹包含在 中的include设置中tsconfig,这很糟糕,因为它内置在dist目录中。

安装的开发依赖项: jest ts-jest @types/jest

tsconfig.json

{
  "compilerOptions": {
    "sourceMap": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "allowJs": true,
    "jsx": "react",
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"], …
Run Code Online (Sandbox Code Playgroud)

typescript tsconfig jestjs visual-studio-code ts-jest

7
推荐指数
1
解决办法
2205
查看次数

如何用玩笑模拟 fs.readFileSync

在我的 app.js 中我有这个函数:

const bodyParser = require('body-parser')
const express = require('express')
const app = express()
const cors = require('cors')
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
const dataFilePath = '../shoppinglist/data.json'
const baseUrl = '/api/v1/shoppingLists'
let client
const fileSystem = require('fs')
let data



app.post(baseUrl, (req, res) => {
    const newData = req.body
    if(newData != null && !isEmpty(newData) && isRequiredFieldGiven(newData)){
        readUpdatedData()
        newData.id = getNewestId()
        data.data.push(newData)
        //updateData(data)
        console.log(data)
        res.setHeader('Content-Type', 'application/json')
        res.statusCode = 201
        res.json({"Location" : baseUrl + '/' + newData.id})
    }else{
        res.statusCode = 400
        res.send() …
Run Code Online (Sandbox Code Playgroud)

javascript mocking node.js express jestjs

5
推荐指数
1
解决办法
2万
查看次数

从 CLI 生成的新 vue 3 项目中获取单元测试错误

我使用 vue cli 创建了一个具有以下规范的新项目:

  • 视图 3
  • 打字稿
  • 没有类语法
  • Vue路由器
  • 通天塔
  • eslint + 标准
  • 笑话

当我运行时npm run test:unit出现以下错误

TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
    tests/unit/example.spec.ts:7:34 - error TS2769: No overload matches this call.
      The last overload gave the following error.
        Argument of type 'DefineComponent<readonly string[] | Readonly<ComponentObjectPropsOptions<Record<string, unknown>>>, unknown, unknown, Record<string, ComputedGetter<any> | WritableComputedOptions<...>>, ... 7 more ..., { ...; } | {}>' is not assignable to parameter of type 'ComponentOptionsWithObjectProps<readonly string[] | Readonly<ComponentObjectPropsOptions<Record<string, unknown>>>, unknown, unknown, Record<string, …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing typescript vue.js jestjs

5
推荐指数
2
解决办法
2612
查看次数

如何正确模拟 i18next

这是我的函数和测试的简化版本。虽然我嘲笑了 useTranslation 我收到以下错误:

您正在传递一个未定义的模块!请检查您传递给 i18next.use() 的对象

   7 | i18n
   8 |   .use(Backend)
>  9 |   .use(initReactI18next)
Run Code Online (Sandbox Code Playgroud)

我如何正确模拟以消除此错误?

import React from 'react'
import { useTranslation } from 'react-i18next'
import * as Constants from 'constants'
import MyComponent from 'components'

const Dashboard = () => {
  const { t } = useTranslation('dashboard')
  return (
     <div> Dashboard 
      <MyComponent name={t(Constants.MYCOMPONENT)}/>
    </div>
  )
}

export default Dashboard
Run Code Online (Sandbox Code Playgroud)
jest.mock('react-i18next', () => ({
  useTranslation: () => ({ t: (key) => key })
}))
it('Render Dashboard without crash', () …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs enzyme react-i18next

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

使用笑话和酶模拟自定义 Hook 会导致“xxx 不是函数或其返回值不可迭代”错误

我对笑话和酶很陌生。在我的项目中,我将使用基于 SPA React 的应用程序。包含数据的上下文提供程序,还有几个钩子。我现在使用 Jest(带有 ts-jest 和酶)

\n

我的 jest.config 看起来像这样

\n
module.exports = {\n  "roots": [\n    "<rootDir>/src"\n  ],\n  "transform": {\n    "^.+\\\\.tsx?$": "ts-jest"\n  },\n  "testRegex": "(/__tests__/.*|(\\\\.|/)(test|spec))\\\\.tsx?$",\n  "moduleFileExtensions": [\n    "ts",\n    "tsx",\n    "js",\n    "jsx",\n    "json",\n    "node"\n  ],\n  "snapshotSerializers": ["enzyme-to-json/serializer"]\n
Run Code Online (Sandbox Code Playgroud)\n

所以我的第一步是测试 UI 组件是否有效。\n下一步是使用模拟数据测试组件。但我得到了底部描述的错误。

\n

我有一个像这样的功能组件:

\n
export default function CurrentWeather(props: ICurrentWeatherProps) {\n    const [data, Reload] = useCurrentWeather(props.locationID);\n    return (<div>......</div>)\n}\n\n
Run Code Online (Sandbox Code Playgroud)\n

您会注意到这个useCurrentWeather钩子,这是其代码:

\n
import { useEffect, useState } from 'react';\nimport { useLocationState } from '../context/locationContext';\nimport { ILocationData } from './useLocations';\nimport _ …
Run Code Online (Sandbox Code Playgroud)

jestjs enzyme react-scripts ts-jest react-typescript

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

npm WARN弃用minimatch@2.0.10:请更新到minimatch 3.0.2

$ npm update minimatch@3.0.2

$ npm update -d
npm info it worked if it ends with ok
npm info using npm@2.11.3
npm info using node@v0.12.7
npm info attempt registry request try #1 at 5:33:55 PM
npm http request GET https://registry.npmjs.org/jshint
npm http 200 https://registry.npmjs.org/jshint
npm info ok


$ npm install jshint
npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher                                                                                                                 to avoid a RegExp DoS issue
npm WARN deprecated minimatch@0.3.0: Please update to minimatch 3.0.2 or higher                                                                                                                 to …
Run Code Online (Sandbox Code Playgroud)

npm ionic-framework

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