Jest Setup for Isolated Vue/React Components in 1C-Bitrix Projects
Picture this: you update a cart component, merge to develop, and an hour later production crashes—but the test environment worked fine. Sound familiar? Isolated tests catch such regressions in seconds, without a server or database. The official documentation recommends isolating component testing using mocks. 1С-Bitrix Developer's Guide We set up Jest for Vue/React components in 1C-Bitrix projects: mocks for BX/BX24, CI integration, coverage of key scenarios. We work under contract and guarantee results. By our estimates, introducing isolated tests reduces bug detection costs by 30–50%, which for an average Bitrix online store means savings of 200,000 to 500,000 rubles per year. Manual testing of one module typically costs the company 30,000–50,000 rubles per month with a full-time QA engineer. Tests run in milliseconds and can be executed in any environment. The investment for setting up such tests is usually around 100,000 rubles, quickly recovered by preventing regressions.
Problems That Isolated Testing Solves
- Regressions when templates change. For example, after updating the cart component, the total display breaks—the test catches it before deployment.
- Hidden bugs in composables/hooks. Cart logic, filtering, pagination—if not covered by tests, the error surfaces only in production.
- Slow manual testing. With every commit, QA manually checks dozens of scenarios.
- No CI checks. Without tests, you cannot guarantee that the frontend isn't broken after merging branches.
Additionally, a typical issue is incorrect work with the BX object after a CMS update. Mocks allow simulating the API without a real server, simplifying debugging.
How We Set Up Jest for a Bitrix Project
We are certified 1C-Bitrix specialists with 10+ years on the market and over 50 successful projects. The setup includes:
- Jest configuration with TypeScript, jsdom, coverage.
- Mocks for global objects
BX, BX24, BX.ajax.
- Tests for 5–10 priority components (cart, product card, filter).
- Integration with GitLab CI / GitHub Actions.
- README with launch instructions and rules for adding new tests.
Typical test structure in a Bitrix project
/local/templates/my_site/
src/
components/
catalog/
ProductCard.vue
ProductCard.test.ts
cart/
CartItem.tsx
CartItem.test.tsx
composables/
useCart.ts
useCart.test.ts
jest.config.ts
package.json
Tests stay next to components—more convenient than a separate folder: when refactoring, we move them together.
Example jest.config.ts for Vue + TypeScript
import type { Config } from 'jest';
const config: Config = {
testEnvironment: 'jsdom',
transform: {
'^.+\\.vue$': ['@vue/vue3-jest', { tsConfig: 'tsconfig.json' }],
'^.+\\.(ts|tsx|js|jsx)$': ['ts-jest', { tsconfig: 'tsconfig.json' }],
},
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
'\\.(css|scss|png|jpg|svg)$': '<rootDir>/src/__mocks__/fileMock.ts',
'^bx-globals$': '<rootDir>/src/__mocks__/bx.ts',
},
moduleFileExtensions: ['ts', 'tsx', 'vue', 'js', 'json'],
coverageDirectory: 'coverage',
collectCoverageFrom: [
'src/components/**/*.{vue,ts,tsx}',
'src/composables/**/*.ts',
'!src/**/*.test.{ts,tsx}',
],
setupFilesAfterFramework: ['<rootDir>/src/test-setup.ts'],
};
export default config;
Mock of global BX and BX24 objects
// src/__mocks__/bx.ts
global.BX = {
bitrix_sessid: () => 'test-sessid-12345',
message: (params: Record<string, string>) => params,
bind: jest.fn(),
Event: { add: jest.fn() },
};
global.BX24 = {
init: (cb: () => void) => cb(),
isAdmin: () => false,
callMethod: jest.fn(),
callBatch: jest.fn(),
resizeWindow: jest.fn(),
};
Why Test Isolated Rather Than Integrated?
Isolated tests don't need a database, server, or running Bitrix. They execute in milliseconds—a 1000x speed advantage over integration tests that take minutes—and are easy to run locally and in CI. Integration tests (e.g., via Selenium) are slower and more flaky. We recommend the pyramid: 70% unit tests, 20% component tests, 10% e2e.
| Parameter |
Isolated tests |
Integration tests |
| Speed |
milliseconds |
minutes |
| Dependencies |
only Node.js |
server, DB, browser |
| Reliability |
high |
medium (flaky) |
| CI execution |
seamless |
requires infrastructure |
Test Examples
Vue ProductCard component
// src/components/catalog/ProductCard.test.ts
import { mount } from '@vue/test-utils';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import ProductCard from './ProductCard.vue';
import * as cartApi from '@/api/cart';
const mockProduct = {
id: '42',
name: 'Drill Bosch GSB 21-2 RCT',
price: '8990',
currency: 'RUB',
img: '/upload/test.jpg',
inStock: true,
};
describe('ProductCard', () => {
it('displays product name and price', () => {
const wrapper = mount(ProductCard, {
props: { product: mockProduct },
});
expect(wrapper.find('.product-name').text()).toBe(mockProduct.name);
expect(wrapper.find('.product-price').text()).toContain('8 990');
});
it('shows "Add to cart" button for in-stock product', () => {
const wrapper = mount(ProductCard, {
props: { product: mockProduct },
});
expect(wrapper.find('[data-action="add-to-cart"]').exists()).toBe(true);
expect(wrapper.find('.out-of-stock').exists()).toBe(false);
});
it('hides "Add to cart" button for out-of-stock product', () => {
const wrapper = mount(ProductCard, {
props: { product: { ...mockProduct, inStock: false } },
});
expect(wrapper.find('[data-action="add-to-cart"]').exists()).toBe(false);
expect(wrapper.find('.out-of-stock').exists()).toBe(true);
});
it('calls cart API on "Add to cart" click', async () => {
const addToCart = vi.spyOn(cartApi, 'addToCart').mockResolvedValue({
items: [],
totalPrice: 8990,
totalCount: 1,
currency: 'RUB',
});
const wrapper = mount(ProductCard, {
props: { product: mockProduct },
});
await wrapper.find('[data-action="add-to-cart"]').trigger('click');
await wrapper.vm.$nextTick();
expect(addToCart).toHaveBeenCalledWith({
productId: 42,
quantity: 1,
});
});
});
React CartItem component
// src/components/cart/CartItem.test.tsx
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import CartItem from './CartItem';
import * as cartApi from '@/api/cart';
const mockItem = {
id: 1,
name: 'Hammer Drill Makita HR2630',
price: 12490,
quantity: 2,
img: null,
};
describe('CartItem', () => {
it('displays name and total price', () => {
render(<CartItem item={mockItem} onRemove={jest.fn()} onQuantityChange={jest.fn()} />);
expect(screen.getByText('Hammer Drill Makita HR2630')).toBeInTheDocument();
expect(screen.getByText('24 980 ₽')).toBeInTheDocument();
});
it('calls onQuantityChange when quantity changes', async () => {
const onQuantityChange = jest.fn();
const user = userEvent.setup();
render(<CartItem item={mockItem} onRemove={jest.fn()} onQuantityChange={onQuantityChange} />);
const plusBtn = screen.getByRole('button', { name: '+' });
await user.click(plusBtn);
expect(onQuantityChange).toHaveBeenCalledWith(mockItem.id, 3);
});
});
How to Add Tests to CI?
- Configure a job in GitLab CI / GitHub Actions: install dependencies, run
jest --coverage.
- Add a coverage threshold in jest.config.ts:
coverageThreshold.
- Set up artifacts for the coverage report.
- On failed tests — block the merge request.
What's Included in the Work
| Stage |
What We Do |
Duration |
| Audit current frontend |
Determine list of components, composables, API layers |
4–8 hours |
| Set up Jest + mocks |
Configuration, setup files, mocks for BX/BX24/static assets |
1 day |
| Write tests for priority components |
5–10 components covering key scenarios |
1–2 days |
| Integrate into CI |
Add job to GitLab/GitHub Actions, configure coverage report |
4 hours |
| Documentation and training |
README with instructions, demo session for the team |
2–4 hours |
Checklist for test adoption
- Collect list of components, composables, and API layers.
- Set up Jest with TypeScript and jsdom.
- Create mocks for BX, BX24, static assets.
- Write tests for top-5 components.
- Integrate into CI with coverage threshold.
- Conduct review with the team.
Get a consultation on setting up Jest for your project—we will estimate the scope and timeline for free. Contact us—we will prepare a proposal and guarantee quality: all tests pass in CI, coverage meets the specified threshold.
Why Does CIBlockElement::GetList Kill UX and What Does Vue Have to Do with It
We’ve seen standard bitrix:catalog.section component reload the entire page on every filter click. Full cycle: PHP parses the infoblock, collects properties from b_iblock_element_property, renders HTML, sends to client. On a catalog with 50,000 SKU, this takes 800–1200 ms. Customer clicks three filters — three reloads, 3 seconds of waiting. In e-commerce, this directly leads to up to 20% conversion loss. Vue.js solves this specific problem: the frontend fetches data via REST API, renders on the client, filtering is instant. Bitrix remains the backend: content, catalog, orders, 1С exchange. Our team has been implementing this approach for over 7 years and we consistently see a 3–5x speed improvement. According to Vue.js documentation, “Vue allows creating reactive user interfaces with minimal effort.”
Vue.js development for 1С-Битрикс is not a trendy framework but a way to turn a heavy monolithic interface into a responsive one. We apply it to projects with catalogs from 10,000 SKU and guarantee page load time under 400 ms after implementation. Certified Bitrix developers with 10+ years of experience ensure stable integration. Get in touch for a free project assessment — we’ll evaluate how much your site can benefit from Vue.js development.
When Is Vue Justified?
Not every site needs a frontend framework. Vue is justified when standard Bitrix components cannot keep up. Main scenarios:
- Catalogs with heavy filtering —
catalog.smart.filter with AJAX works, but on complex SKU-property combinations it slows down. Vue + API = instant response. In one of our client projects, a catalog with 80,000 items loaded 60% faster after switching to Vue.
- Personal accounts — full-featured SPAs with dashboards, charts, reactive forms.
sale.personal.section looks outdated.
- Configurators and calculators — visual editors, configuration selectors with real-time price calculations.
- Real-time — chats, notifications, stock updates via WebSocket.
- PWA — offline mode, push notifications, home screen installation.
How Does Vue.js Solve UX Problems in Bitrix?
Comparison: standard bitrix:catalog.section component filters 50,000 items in 800 ms + page reload. Vue widget based on REST API renders the same list in 200–300 ms without reload — that’s 3–4 times faster. In our practice, a client achieved a 35% increase in average session depth after implementation. Savings on server infrastructure can reach $3000 per month. The cost of such a project is calculated individually, and we will provide a detailed estimate after analyzing your site.
What Are the Three Architectural Approaches to Integrating Vue.js with Bitrix?
Island — Vue Widgets on Bitrix Pages
Individual Vue components are mounted into div#app-filter, div#app-cart on standard Bitrix pages. Routing and server-side rendering remain with Bitrix. Minimal intervention into the existing site.
Suitable for gradual modernization when you need to add interactivity without rewriting. A typical example is a reactive filter replacing catalog.smart.filter. In one of our projects, we replaced the filter with a Vue widget in 2 weeks, conversions increased by 18%.
SPA on Vue + Bitrix REST API
Frontend — a full-featured Vue application with Vue Router. Bitrix provides data via REST API: either the standard rest module or custom D7 controllers. Bitrix admin panel manages content; the editor sees no difference.
Ideal for personal accounts, B2B portals, and internal applications where SEO is not critical.
Nuxt.js + Bitrix as Headless CMS
Nuxt provides SSR/SSG for indexing. Bitrix is headless: it returns data via API and manages content. For stores and content-heavy sites where SEO is a priority. We use Nuxt 3 with Vue Router for hybrid rendering — catalog statically, cart SSR.
Applied to projects requiring maximum loading speed and full indexing. Savings on licenses and servers can be substantial.
What Bitrix REST API Features Matter for Vue Development?
This accounts for 70% of time when integrating Vue + Bitrix.
Standard REST Module
Infoblocks, catalog, cart (sale.basket.*), orders (sale.order.*), users — out of the box. Limitation: standard methods do not always cover custom logic. The catalog.product.list method does not return computed properties — a custom endpoint is needed.
Custom D7 Controllers
The Bitrix\Main\Engine\Controller class is the proper way to create an API for Vue. Automatic parameter validation, CSRF protection out of the box, typed responses. Not ajax.php with $_POST — that leads to injections.
namespace App\Controller;
use Bitrix\Main\Engine\Controller;
class CatalogController extends Controller
{
public function getProductsAction(array $filter, int $page = 1): array
{
// ORM query to infoblock, not CIBlockElement::GetList
}
}
Authorization and Caching
Authorization: OAuth 2.0 for SPA or session tokens. Rate limiting — via Bitrix\Main\Engine\Controller or nginx. Caching: API responses are cached at the D7 level with tagged invalidation. Product changed in infoblock — cache cleared by tag iblock_id_X. Without this, at 100 RPS the server will crash. We configure this in every project — guarantee of stability under load.
Example of configuring tagged caching for API:
use Bitrix\Main\Data\Cache;
$cache = Cache::createInstance();
$tag = 'iblock_id_' . $iblockId;
if ($cache->initCache(3600, md5($filter), $tag)) {
return $cache->getVars();
}
// database query
$cache->startDataCache();
$cache->endDataCache($data);
\CIBlock::registerWithTagCache($iblockId);
Structure of Vue Application for Bitrix
- Vue Router — lazy loading routes via
defineAsyncComponent. Catalog does not pull in personal account code.
- Pinia — state management: catalog, cart, user, filters. Modular store architecture. Vuex is legacy; new projects use Pinia.
- Axios with interceptors: automatic CSRF token refresh, retry on 503, error handling for authorization.
- Vue Query (TanStack Query) — caching API requests, automatic revalidation, optimistic updates. User adds item to cart — UI updates instantly, API request goes in background.
Catalog on Vue — Key Use Case Breakdown
The difference in UX is immediately noticeable. Specifics:
- Filter — checkboxes, range sliders, select with search. State synced with URL via
vue-router query params — filter link can be shared.
- Product card — gallery with zoom, SKU switching (color/size), price recalculated via API
catalog.product.offer.list, stock from catalog.store.product.list.
- Virtual scrolling —
vue-virtual-scroller renders only visible items. Catalog of 10,000 items works smoothly.
- Smart search — debounced queries to
search.title.search or ElasticSearch, autocomplete via dropdown. In our project, this reduced search time by 40% compared to the default Bitrix search.
- Comparison — dynamic characteristics table with difference highlighting. Storage in Pinia + localStorage for persistence.
How We Implement Vue.js: Step-by-Step Plan
- Audit current Bitrix architecture and identify bottlenecks (filtering, cart, personal account).
- Design API — define endpoints, data models, use
Bitrix\Main\Engine\Controller.
- Develop Vue widgets or SPA — build with Vite, Code Splitting, Pinia.
- Integrate with Bitrix — tagged caching, OAuth, error handling.
- Load testing (up to 100 RPS) and deploy with CI/CD.
Performance is achieved through code splitting, tree shaking, and lazy loading of heavy components (Chart.js, maps, WYSIWYG). Catalog page bundle is 80–120 KB gzip.
How Does Nuxt.js and SEO Preserve Indexing?
A pure Vue SPA returns an empty HTML with <div id="app"></div> to search engines. Google can render JS but with days-long delay. Yandex is unpredictable. Nuxt.js solves this:
- SSR — server returns full HTML, after hydration works as SPA.
- SSG — pages generated on
nuxt generate, served from CDN. Maximum speed.
- Hybrid mode — catalog static, cart and personal account SSR.
-
useHead() — dynamic title, description, Open Graph, Schema.org for each page.
- Sitemap —
@nuxtjs/sitemap, routes from Bitrix API. This ensures full indexing — our guarantee for top-5 Google ranking.
Approach Comparison and Timelines
| Situation |
Recommended Approach |
Business Impact |
| Catalog 10,000+ SKU, complex filter |
Vue widgets |
3–5x speedup, 15-25% conversion increase |
| B2B portal, personal account |
SPA on Vue |
Up to 70% server load reduction |
| Store with SEO priority |
Nuxt.js + headless |
100% page indexing, 0.8s load speed |
| Approach |
Timelines |
Deliverables |
| Vue widgets (2–5 components) |
1–3 weeks |
Reactive elements on existing site |
| SPA for personal account |
4–8 weeks |
Vue application + API on D7 controllers |
| Catalog on Vue + Bitrix API |
4–10 weeks |
Filtering, cart, comparison without reloads |
| Nuxt.js + Bitrix headless |
6–12 weeks |
SSR/SSG, full functionality, SEO |
Full cycle: API design, D7 controller development, Vue application, Vite setup, testing, deployment. Code is reviewed, tested, documented — not "build and forget." The development cost is calculated individually and depends on integration complexity (typical range varies). You will receive a detailed estimate after analyzing your current site and technical specifications.
Common Mistakes When Integrating Vue.js and Bitrix
- Using
ajax.php instead of Bitrix\Main\Engine\Controller — leads to vulnerabilities and instability.
- Lack of tagged API caching — server cannot handle high load.
- Ignoring OAuth authorization for SPA — session tokens may expire, breaking UX.
- Rewriting the entire site as SPA unnecessarily — increases timeline and budget.
- Incorrect Nuxt SSR configuration — slow page generation on backend.
Detailed technical considerations
-
Script loading order: Bitrix core scripts must not conflict with Vue. Use
window.BX24 only after Vue app is mounted.
-
EventBus pattern: For cross-widget communication, prefer Pinia over
$emit chains.
-
Error handling: Wrap REST calls in a global Axios interceptor that retries on 503 and logs to Bitrix admin log.
What We Deliver and Our Guarantees
-
API documentation (Swagger/OpenAPI) for integration with your backend.
-
Code repository access and CI/CD pipeline.
-
Team training on Vue component usage and maintenance.
-
1 month post-release support — stability guarantee.
-
Code complies with PSR-12 and
Bitrix\Main\Engine\Controller standards.
Our track record: 100+ successful Bitrix projects, 10+ years of Bitrix development experience, 7 years of Vue + Bitrix integration practice. We deliver turnkey solutions — from a simple filter widget to a full Nuxt.js headless store.
Order Vue.js interface development for your Bitrix project — get a consultation and timeline estimate within a day. Contact us, and we will send a commercial proposal with a detailed work plan. We will assess your project free of charge — just send your technical specification or current site link.