所以我对redux-store的实现可能不是最好的,而且我对Jest的了解是最小的.
我有三个文件,包括......
我的测试文件如下所示:
// file.test.js
jest.mock( 'store', () => jest.fn() )
// external
import React from 'react'
import configureStore from 'redux-mock-store'
// internal
import Component from 'components/Component'
import store from 'store'
describe( 'Test My Component', () => {
const mockStore = configureStore()
it ( 'should equal true', () => {
const initialState = { active: true }
store.mockImplementation(() => mockStore( initialState ))
expect( store.getState().active ).toBe( true )
} )
} );
Run Code Online (Sandbox Code Playgroud)
我嘲笑商店的原因是因为<Component />我正在使用一个模块,它本身导入相同的store并且拥有一些正在利用的功能 …
我想测试一下,当从React组件调用一个方法时,它会触发一个函数传递给组件作为道具.方法是这样的:
customMethod() {
// Do something
this.props.trackEvent({
category: 'eventCategory',
action: 'eventAction',
label: 'eventAction',
});
// Do something else
}
Run Code Online (Sandbox Code Playgroud)
可以通过不同的方式调用该方法,因此我只想进行一般测试:如果调用了customMethod,则应该使用数据触发this.props.trackEvent.
有没有办法用jest和/或酶触发方法调用?我读到过这样的事情:
const wrapper = shallow(<AdPage {...baseProps} />);
wrapper.instance().customMethod();
Run Code Online (Sandbox Code Playgroud)
但它不起作用......任何想法.我在测试中很新,所以我应该使用不同的方法进行这种测试?
class TestObject {
constructor(value) {
if (value === null || value === undefined) {
throw new Error('Expect a value!');
}
}
}
describe('test the constructor', () => {
test('it works', () => {
expect(() => {
new TestObject();
}).toThrow();
});
test('not work', () => {
expect(new TestObject()).toThrow();
});
});
Run Code Online (Sandbox Code Playgroud)
2这里的测试用例,一个工作,另一个不工作.
该消息的失败消息not work如下:
●测试构造函数>不工作
期待一个价值!
Run Code Online (Sandbox Code Playgroud)at new TestObject (tests/client/utils/aaa.test.js:4:11) at Object.<anonymous> (tests/client/utils/aaa.test.js:17:12) at Promise (<anonymous>) at <anonymous> at process._tickCallback (internal/process/next_tick.js:188:7)
为什么我需要在函数调用中包装该调用,当函数只返回一个普通值,甚至是一个promise时,我们不需要包装,我们可以用它async/await来检查expect()而不是在里面创建一个函数expect().
这里发生了什么?
只是新的反应,react-redux/saga和jest
考虑:
----- Componnent()----
componentDidMount() {
this.props.actions.initTodos(
axios,
ajaxURLConstants.WP_GET_TODOS,
appStateActions.setAppInIdle,
appStateActions.setAppInProcessing,
todosActions.todosInitialized
);
}
Run Code Online (Sandbox Code Playgroud)
因此,当我的TodoApp组件安装时,它将调度INIT_TODOS操作,然后我的根传奇正在侦听,当它捕获它时,将生成相应的工作者传奇以相应地执行操作.
-----相应的工人传奇-----
export function* initTodosSaga( action ) {
try {
yield put( action.setAppInProcessing() );
let response = yield call( action.axios.get , action.WP_GET_TODOS );
if ( response.data.status === "success" )
yield put( action.todosInitialized( response.data.todos ) );
else {
console.log( response );
alert( response.data.error_msg );
}
} catch ( error ) {
console.log( "error" , error );
alert( "Failed to load initial …Run Code Online (Sandbox Code Playgroud) 我们使用jest来测试我们的API并且具有非常复杂的场景.我们使用这些beforeAll函数为每个测试设置一般辅助变量,有时设置租户分离,在其他情况下,我们使用beforeEach函数为测试设置租户分离,为测试租户设置一些默认配置,...
例如,测试可能喜欢这样的东西(正如你所看到的,我们使用TypeScript来编写测试,以防万一):
let apiClient: ApiClient;
let tenantId: string;
beforeAll(async () => {
apiClient = await getClientWithCredentials();
});
beforeEach(async () => {
tenantId = await createNewTestTenant();
});
describe('describing complex test scenario', () => {
it('should have some initial state', async () => {
await checkState(tenantId);
});
it('should have some state after performing op1', async () =>{
await op1(tenantId);
await checkStateAfterOp1(tenantId);
});
it('should have some state after performing op2', async () =>{
await op2(tenantId);
await checkStateAfterOp2(tenantId);
});
it('should …Run Code Online (Sandbox Code Playgroud) 我正在与Typescript和Jest一起尝试为我的Angular和Ionic应用程序测试某些组件,但是问题不仅仅限于Angular或Ionic。因此,我正在尝试使Jest的模拟功能起作用。
我只是在创建一个虚拟类,我想尝试模拟函数的响应以查看是否可以覆盖行为。
开玩笑
export class AClass {
constructor() { }
GetOne():any {
return 1;
}
GetTwo():any {
return 2;
}
}
Run Code Online (Sandbox Code Playgroud)
玩笑样张
import { AClass } from './jest-mock';
// const mockGet = jest.fn( () => { return 3; } ); // Tried this to return 3?
const mockGet = jest.fn();
jest.mock('./jest-mock', () => {
return jest.fn().mockImplementation( () => {
return { GetOne: mockGet };
});
});
describe('Testing Jest Mock is working', () => {
it('should support mocking out the component', …Run Code Online (Sandbox Code Playgroud) 我在测试我的thunk时遇到了问题,因为我的许多API调用都在使用FormData,而我似乎无法弄清楚如何在测试中模拟它.我正在使用Jest.
我的安装文件如下所示:
import 'isomorphic-fetch';
// Mocking the global.fetch included in React Native
global.fetch = jest.fn();
// Helper to mock a success response (only once)
fetch.mockResponseSuccess = body => {
fetch.mockImplementationOnce(() =>
Promise.resolve({ json: () => Promise.resolve(JSON.parse(body)) })
);
};
// Helper to mock a failure response (only once)
fetch.mockResponseFailure = error => {
fetch.mockImplementationOnce(() => Promise.reject(error));
};
Run Code Online (Sandbox Code Playgroud)
但是,我在所有需要FormData的测试中收到以下错误:
ReferenceError: FormData is not defined
Run Code Online (Sandbox Code Playgroud)
我试图从导入FORMDATA文件react-native-mock,下src/Libraries/Network/FormData,但没有奏效.
所以我想知道是否有人有这样的运气?
总的来说,我很难找到fetch在React Native中模拟请求的最佳方法,所以这里的任何建议都会很好.我已经尝试了jest-fetch-mocklib(并打开了一个关于FormData的问题),尝试设置nock(没有运气),这个简单的Jest实现,但还没有感觉到.
真的在这里争斗.
我的Circle CI测试失败了
FAIL ./App.test.js
? Test suite failed to run
SyntaxError: Unexpected token )
Run Code Online (Sandbox Code Playgroud)
我尝试在我的机器上本地运行Jest(一个CRNA)但我收到以下错误:
TypeError: environment.setup is not a function
所以这两个似乎都是节点版本/ ES6/babel问题,对吧?
我在(Path was expecting string等)之前遇到了一些错误,我通过安装jest-cli和更改节点版本等来解决这个问题.
我现在在: 节点 v8.9.1 npm 5.5.1
但现在我完全难过了.
所以:
TypeError: environment.setup is not a function 特定于jest-cli包.
我试过了:
i)在pkg json中将以下内容添加到jest配置中:
"jest": {
"preset": "jest-expo",
"testMatch": [
"*.test.js",
"**/?(*.)(spec|test).js?(x)"
],
"transformIgnorePatterns": [
"node_modules/(?!(react-native|jest-cli)/)"
]
}
Run Code Online (Sandbox Code Playgroud)
(认为这可能是'babel'模块,但是错误消息没有变化)
ii)更改babel-core版本,安装babel-node-modules,更改React Native版本,开玩笑等等.没有快乐.
救命?
在获取Create React Native App项目以在节点v5-v8上运行jest测试方面,我是否缺少一些东西?
正确难倒,它正在阻止我的Circle CI设置.
发送帮助或某种IPA啤酒来减轻我的沮丧.
我有一个实用程序文件,其中包含许多导出以及默认导出.命名和导出默认值都在同一个组件中使用.我无法确定如何针对同一测试中的命名和默认组件编写测试.
下面的代码以简化的方式说明了应用程序.如果我遗漏了一些重要的东西,请告诉我.谢谢!
utils.js
export const mock1svc = () => {
return true;
};
const mock2svc = () => {
return true;
};
export default mock2svc;
Run Code Online (Sandbox Code Playgroud)
comp.js (fyi,app呈现罚款)
import Utils, { mock1svc } from 'utils';
...
render (
<p>{mock1svc()}</p>
<p>{Utils()}</p>
)
Run Code Online (Sandbox Code Playgroud)
comp-test.js
我可以测试默认导出:
jest.mock('../mock-utils', () => jest.fn());
生成错误: TypeError: (0 , _mockUtils.mock1svc) is not a function
或测试命名导出:
jest.mock('../mock-utils', () => ({
mock1svc: jest.fn(),
mock2svc: jest.fn(),
}));
Run Code Online (Sandbox Code Playgroud)
生成错误: TypeError: (0 , _mockUtils.default) is not a function
我尝试了各种方法,但都失败了.
非常感谢您提供的任何帮助!
法案
我在许多测试套件中,在许多测试文件中进行了许多测试
我需要隔离和调试单个测试
我正在调试通过node --inspect-brk ./node_modules/jest/bin/jest,所以其他涉及监视模式的解决方案太复杂了
我怎么能跳过所有测试,除了我需要调试的那个?
jest ×10
javascript ×4
testing ×3
unit-testing ×3
react-native ×2
reactjs ×2
typescript ×2
async-await ×1
babel ×1
ecmascript-6 ×1
enzyme ×1
es6-class ×1
fetch-api ×1
mocking ×1
node.js ×1
redux-saga ×1
redux-store ×1