我正在将 Jest 测试用例运行到一个 ReactJS 项目中。我正在尝试在 VS code 中调试我的笑话测试用例。测试在命令行上运行正常。但是当我在 VS Code 中启动调试器时,我看到错误。
启动.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Jest Tests",
"program": "${workspaceRoot}/xxx/xxx/node_modules/jest/bin/jest",
"args": [
"-i"
],
"internalConsoleOptions": "openOnSessionStart",
"outFiles": [
"${workspaceRoot}/xxx/xxx/**/*"
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
Debugger listening on ws://127.0.0.1:31182/2bf113f1-002f-49ed-ad91-5510affd172a
Debugger attached.
Error: Could not find a config file based on provided values:
path: "/Users/xxx/xxx/xxx-ui"
cwd: "/Users/xxx/xxx/xxx-ui"
Configh paths must be specified by either a direct path to a config
file, or a path to …Run Code Online (Sandbox Code Playgroud) 假设我有一个类组件,它有这样的东西:
export class Math extends React.Component {
...
someComponentMethod = numb => {
const sample = numb * 10
...
const result = numb -5
return result
}
Run Code Online (Sandbox Code Playgroud)
是否可以sample在 Jest 中对变量进行测试断言?
我是使用React-Jest-Enzyme进行测试的新手,但是根据我收集到的所有信息,在我看来,大多数测试实际上都会测试React库是否中断,而不是我的实际业务逻辑.
我会给你一些例子,如果我错了,请纠正我:
这个策略有什么用?
从我看到它的主要目的是捕获我的代码的任何不需要的更改.它" stringify "我的组件树,只是注意到是否添加了任何新的换行符,对吧?
所以它主要用于那些我可能会意外按下键盘的情况?或其他人意外地弄乱我的代码?
我看到的大多数示例解释了你使用它们的方式是这样的:
const wrapper = mount(<MyComponeny />)
expect(wrapper.find(‘button’).simulate(‘click)).toHaveBeenCalledTime(1)
Run Code Online (Sandbox Code Playgroud)
我能从中获得什么价值?如果我模拟用酶的按钮点击simulate(‘click’),那么我应该期望它会触发点击事件.
我在这里测试的是什么?酶的功能?
还有setState方法酶给我们.如果wrapper.setState({value: ‘some value’)}想改变我的状态,为什么我会看到这样的用例:
wrapper.setState({value: ‘new value’)}
expect(wrapper.state(‘value’)).toBe(‘new value’)
Run Code Online (Sandbox Code Playgroud)
?
为什么我需要测试测试框架/额外的库?
这一切似乎都有点含糊不清
有没有人为 react-native-tab-view 编写过单元测试?我需要模拟道具 onIndexChanged 和 TabBar 的 getLabelText。这是我们的模拟
import React from 'react';
import { View } from "react-native";
export class TabView extends View {
render = function () {
return <View>
{this.props.renderTabBar()}
{Object.values(this.props.renderScene)
.map((scene, i) => <View key={i}>{scene()}</View>)}
</View>;
};
};
export const TabBar = View;
export const SceneMap = map => map;
Here is the TabView we are using. Any help is really appreciated. Run Code Online (Sandbox Code Playgroud)
<TabView
navigationState={this.state}
renderScene={SceneMap({
current: () => <TorViewCurrent
torCurrentList={this.props.torCurrentList}
torCurrentListLoading={this.props.isLoading || this.props.torCurrentListLoading}
torCurrentListLoaded={this.torCurrentListLoaded}
torCurrentListError={this.props.torCurrentListError}
torStatusMap={this.props.torStatusMap}
torReasonMap={this.props.torReasonMap} …Run Code Online (Sandbox Code Playgroud)我一直有一个很难找到如何使用好资源jest.fn()嘲笑类上打字稿类和方法(如快递Request,Response并NextFunction和save()上一个猫鼬模型的方法。)
例如,假设我有以下模型和控制器:
型号/Foo.ts:
import * as mongoose from "mongoose"
export type FooModel = mongoose.Document & {
owner: mongoose.Schema.Types.ObjectId,
bars: string[]
}
const fooSchema = new mongoose.Schema({
owner: { type: mongoose.Schema.Types.ObjectId, ref: "User", index: true },
bars: [String]
}
export const Foo = mongoose.model<FooModel>("Foo", fooSchema)
Run Code Online (Sandbox Code Playgroud)
控制器/foo.ts:
import { Request, Response, NextFunction } from "express";
import { Foo, FooModel } from "../models/Foo";
export let createFoo = async (req: Request, res: Response, next: …Run Code Online (Sandbox Code Playgroud) 我正在编写单元测试并模拟包“child_process”中的“exec”方法。
__mocks__/child_process.js
const child_process = jest.genMockFromModule('child_process');
child_process.exec = jest.fn()
module.exports = child_process;
Run Code Online (Sandbox Code Playgroud)
这是测试文件:
const fs = require('fs-extra'),
child_process = require('child_process'),
runCassandraMigration = require('../../lib/runCassandraMigration.js')
const defaultArguments = () => {
return {
migration_script_path: './home',
logger: {
error: function () {}
}
};
}
jest.mock("fs-extra")
jest.mock("child_process")
describe('Running cassandra migration tests', function () {
describe('successful flow', function () {
it('Should pass without any errors ', async function () {
let args = defaultArguments();
let loggerSpy = jest.spyOn(args.logger, 'error')
fs.remove.mockImplementation(() => {Promise.resolve()})
child_process.exec.mockImplementation(() => …Run Code Online (Sandbox Code Playgroud) 我正在测试一个有条件地渲染包装组件的组件.我正在使用酶和jest,并且通过shallow()方法呈现根组件.问题是测试Root组件是否包含包装组件.
如何在不使用mount()render方法的情况下测试包装的组件是否存在?
hoc.component.jsx
export function HOC(Component) {
render() {
return <Component />
}
}
Run Code Online (Sandbox Code Playgroud)
wrapped.component.jsx
class WrappedComponent extends React.Component {
...
}
export default HOC(WrappedComponent)
Run Code Online (Sandbox Code Playgroud)
root.component.jsx
class RootComponent extends React.Component {
render() {
return (
condition ? ... :
<WrappedComponent/>
)
}
}
Run Code Online (Sandbox Code Playgroud)
当测试root.component.jsx我想检查是否存在WrappedComponent.
root.component.spec.js 进口{} WrappedComponent从'WrappedComponent'
const wrapper = shallow(<RootComponent {...props}/>);
wrapper.find(WrappedComponent).length => returns 0
Run Code Online (Sandbox Code Playgroud)
如果我记录wrapper.debug(),我会看到以下内容:
...<HOC(WrappedComponent) />
Run Code Online (Sandbox Code Playgroud)
在测试RootComponent时,如何测试WrappedComponent的存在?
我有一个专注于输入的指令。我想测试该指令。唯一的问题是我找不到如何测试输入是否聚焦的问题
这是我简单的模拟组件
<template>
<div v-directive>
<input/>
</div>
</template>
Run Code Online (Sandbox Code Playgroud)
这是我的指令:
import Vue from 'vue'
export const focusInput = () => {
return {
inserted(el: any) {
el.getElementsByTagName('input')[0].focus()
}
}
}
export default Vue.directive('focus-input', focusInput())
Run Code Online (Sandbox Code Playgroud)
这是我的测试:
import Vue from 'vue'
import { mount , createLocalVue} from '@vue/test-utils'
import FocusInputMock from './mockComponents/FocusInputMock.vue'
import {focusInput} from '@/directives/focusInput';
const localVue = createLocalVue()
localVue.directive('directive', focusInput())
test('update content after changing state', () => {
const wrapper = mount(FocusInputMock, {
localVue
})
Vue.nextTick(function () {
expect(wrapper.find('input')) // I …Run Code Online (Sandbox Code Playgroud) 我的目的只是测试一个功能。我无法弄清楚如何正确模拟 firebase。我尝试使用 Jest 文档中的 axios 模拟来保留示例。我有以下代码:
音乐服务.js
import { initializeApp } from "firebase/app";
import "firebase/database";
const firebase = initializeApp({
apiKey: "<API_KEY>",
authDomain: "<PROJECT_ID>.firebaseapp.com",
databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
projectId: "<PROJECT_ID>",
storageBucket: "<BUCKET>.appspot.com",
messagingSenderId: "<SENDER_ID>",
});
export class MusicService {
static getAlbums() {
return firebase.database().ref("albums").once("value")
.then(snapshot => Object.values(snapshot.val()));
}
}
Run Code Online (Sandbox Code Playgroud)
音乐服务.test.js
import firebase from 'firebase/app';
import 'firebase/database';
import { MusicService } from './MusicService';
jest.mock('firebase/app');
jest.mock('firebase/database');
test("test", () => {
firebase.initializeApp.mockImplementation(() => {
database: jest.fn(() => {
return {
ref: jest.fn()
}
})
});
MusicService.getAlbums(); …Run Code Online (Sandbox Code Playgroud) javascript unit-testing firebase jestjs firebase-realtime-database
我想为以下案例编写一个开玩笑的测试用例,因为它显示了分支覆盖率50%并指出了这段代码。
render() {
const {
isExit
} = data;
const text = isExit ? 'Yes' : 'No';
Run Code Online (Sandbox Code Playgroud)
或者
<LabelValue label="New Line" value={isExit ? 'Yes' : 'No'} />
Run Code Online (Sandbox Code Playgroud)
测试用例
it('Should display the data if API status is complete', () => {
const wrapper = shallowWithTheme(<DataPage
orderDetail={{ isExit: true}}
theme={theme}
/>);
// what to write here?
});
Run Code Online (Sandbox Code Playgroud) jestjs ×10
enzyme ×5
javascript ×4
reactjs ×2
unit-testing ×2
express ×1
firebase ×1
jasmine ×1
mongoose ×1
node.js ×1
react-native ×1
snapshot ×1
tdd ×1
testing ×1
typescript ×1
vue.js ×1