我在用 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) 我正在将 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)
我有src
和tests
分开的目录。我遵循了在 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) 在我的 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) 我使用 vue cli 创建了一个具有以下规范的新项目:
当我运行时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) 这是我的函数和测试的简化版本。虽然我嘲笑了 useTranslation 我收到以下错误:
您正在传递一个未定义的模块!请检查您传递给 i18next.use() 的对象
Run Code Online (Sandbox Code Playgroud)7 | i18n 8 | .use(Backend) > 9 | .use(initReactI18next)
我如何正确模拟以消除此错误?
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) 我对笑话和酶很陌生。在我的项目中,我将使用基于 SPA React 的应用程序。包含数据的上下文提供程序,还有几个钩子。我现在使用 Jest(带有 ts-jest 和酶)
\n我的 jest.config 看起来像这样
\nmodule.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我有一个像这样的功能组件:
\nexport 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
钩子,这是其代码:
import { useEffect, useState } from 'react';\nimport { useLocationState } from '../context/locationContext';\nimport { ILocationData } from './useLocations';\nimport _ …
Run Code Online (Sandbox Code Playgroud) $ 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) jestjs ×6
javascript ×3
enzyme ×2
ts-jest ×2
typescript ×2
axios ×1
express ×1
mocking ×1
node.js ×1
npm ×1
reactjs ×1
tsconfig ×1
unit-testing ×1
vue.js ×1