@closeio/backbone-testing-library

中文文档
1.0.0发布于 2020/12/22MITESM + CJS零依赖近 30 天下载 5万

DOM testing utilities with API that mirrors React Testing Library

原始使用文档
文档目录6 节
  1. Why would you want this... It's nearly 2021!?
  2. Installation
  3. Example
  4. render Parameters
  5. render Result
  6. License

Backbone Testing Library

NPM JavaScript Style Guide

DOM testing utilities for Backbone with an API that mirrors React Testing Library.

Interested in working on projects like this? Close is looking for great engineers to join our team!

Why would you want this... It's nearly 2021!?

At Close a large portion of our app is still written in Backbone and we're carefully transitioning this to React. We created this library as a way to write tests on our Backbone components in the style of React Testing Library. This means, as we port components over, we are able to use the same tests with very minimal changes and so minimize regressions in our app. While we wouldn't recommend building a brand new FE app with Backbone, we're open sourcing this to help anyone else looking to transition a legacy codebase.

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's devDependencies. This library also has peerDependencies listings for @testing-library/dom:

npm install --save-dev @closeio/backbone-testing-library @testing-library/dom

or

for installation via yarn

yarn add --dev @closeio/backbone-testing-library @testing-library/dom

You may also be interested in installing @testing-library/jest-dom so you can use the custom jest matchers.

Example

// models/HiddenMessageModel.js

import Backbone from 'backbone';

const HiddenMessageModel = Backbone.Model.extend({
  defaults: {
    message: '',
    showMessage: false,
  },
});

export default HiddenMessageModel;
// views/HiddenMessageView.js

import Backbone from 'backbone';

const HiddenMessageView = Backbone.View.extend({
  events: {
    'change #toggle': 'setShowMessage',
  },

  initialize({ model }) {
    this.model = model;
    this.model.on('change', this.render.bind(this));
  },

  setShowMessage(e) {
    this.model.set('showMessage', e.target.checked);
  },

  template({ showMessage, message }) {
    return `<div>
      <label for="toggle">Show Message</label>
      <input
        id="toggle"
        type="checkbox"
        ${showMessage ? 'checked' : ''}
      />
      ${showMessage ? message : ''}
    </div>`;
  },

  render() {
    this.$el.html(this.template(this.model.attributes));
  },
});

export default HiddenMessageView;
// views/HiddenMessageView.test.js

// these imports are something you'd normally configure Jest to import for you
// automatically. Learn more in the setup docs: https://testing-library.com/docs/react-testing-library/setup#cleanup
import '@testing-library/jest-dom';
// NOTE: jest-dom adds handy assertions to Jest and is recommended, but not required

import { render, fireEvent } from '@closeio/backbone-testing-library';

import HiddenMessageModel from '../models/HiddenMessageModel';
import HiddenMessageView from './HiddenMessageView';

test('shows the children when the checkbox is checked', () => {
  const testMessage = 'Test Message';
  const testModel = new HiddenMessageModel({
    message: testMessage,
  });

  // The queries you'd expect from React Testing Library are returned from render, as are
  // `view`, `container`, `baseElement`, `debug` and `unmount`. We also hook into React
  // Testing Library's `RTL_SKIP_AUTO_CLEANUP` const to auto unmount views in `afterEach`
  const { queryByText, getByLabelText, getByText } = render(HiddenMessageView, {
    model: testModel,
  });

  // query* functions will return the element or null if it cannot be found
  // get* functions will return the element or throw an error if it cannot be found
  expect(queryByText(testMessage)).toBeNull();

  // the queries can accept a regex to make your selectors more resilient to content tweaks and changes.
  fireEvent.click(getByLabelText(/show/i));

  // .toBeInTheDocument() is an assertion that comes from jest-dom
  // otherwise you could use .toBeDefined()
  expect(getByText(testMessage)).toBeInTheDocument();
});

render Parameters

  • View - the first argument is the Backbone.View Class to test, it will be instantiated by the render function
  • options - optional - the second argument is an options object with the following parameters:
    • container - optional - behaves like RTL's container by default creates a div and appends it to document.body
    • baseElement - optional - behaves like RTL's baseElement if container is specified, then it defaults to that, otherwise this defaults to document.body
    • autoRender - optional - this defaults to true. Sometimes you may want to assert on something in between your Backbone.View's initialize and render methods, if so you can pass false here and call render manually on the returned view instance.
    • ...options - any other properties will be passed through as options to the Backbone.View's constructor. For example, you could add el if you wanted to manually provide this to the view rather than have Backbone auto create it. You'll also likely often want to pass a model.

render Result

The render method returns an object that has a few properties:

  • ...queries - The most important feature of render is that the queries from DOM Testing Library are automatically returned with their first argument bound to the baseElement, which defaults to document.body
  • view - The Backbone view instance itself.
  • container - behaves like RTL's container returns either a div autocreated for you, or the container passed to render. To get the root element of your rendered element, use container.firstChild or view.el.
  • baseElement - behaves like RTL's baseElement returns either document.body or the baseElement passed to `render.
  • debug - behaves like RTL's debug this function is a shortcut for console.log(prettyDOM(baseElement)).
  • unmount - calls remove on the Backbone.View instance and cleans up the container element. Useful for testing what happens when your view is removed from the page. By default, when RTL_SKIP_AUTO_CLEANUP is false, cleanup is called in every afterEach block which runs render, which means you don't need to manually unmount your views if you're not testing remove. While it might seem odd to rely on a ENV var from another library, our intention here is that this library is run in tandem with RTL and behaves identically for porting components.

License

MIT © Close

版本与发布记录

@closeio/backbone-testing-library 共发布 1 个版本,首次发布于 2020/12/22;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.0.0latest2020/12/225 年前

关于 @closeio/backbone-testing-library 的常见问题

@closeio/backbone-testing-library 是什么?

DOM testing utilities with API that mirrors React Testing Library

如何安装 @closeio/backbone-testing-library?

在项目目录运行 npm install @closeio/backbone-testing-library,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@testing-library/dom(>=6.1.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@closeio/backbone-testing-library 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/closeio__backbone-testing-library 是否存在。

@closeio/backbone-testing-library 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@closeio/backbone-testing-library 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=8。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@closeio/backbone-testing-library 可以商用吗?

@closeio/backbone-testing-library 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@closeio/backbone-testing-library 的下载量有多少?

根据 npm 官方下载统计,@closeio/backbone-testing-library 在 2026/10/10 – 2026/11/08 这 30 天内被下载 50,291 次,日均约 1,676 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@closeio/backbone-testing-library 还在维护吗?

最新版本 1.0.0 发布于 2020/12/22(5 年前);至今共发布 1 个版本,其中过去 12 个月发布了 0 个;首次发布于 2020/12/22。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。