在Mocha中编写Meteor Blaze渲染测试时遇函数不存在错误求助
That error pops up because your Blaze template is trying to call a function named _ that isn’t available in your Mocha test environment. The _ function is most commonly either Underscore/Lodash (used for utility operations) or an i18n helper (like from tap:i18n for translations). Let’s break down how to fix both scenarios:
If you’re using _ for Underscore/Lodash
Meteor includes Underscore by default, but sometimes in test mode, the global _ isn’t exposed properly. Here are two quick fixes:
Explicitly import Underscore in your test file
Add this at the top of your test script to make_available globally for the template to access:import _ from 'underscore'; global._ = _;Pass _ directly to the template context
When rendering the template in your test, include_in the data object to avoid relying on globals:const template = Blaze.renderWithData(Template.yourTemplate, { _: _ }, document.body);
If you’re using _ as an i18n helper (e.g., tap:i18n)
If your template uses {{_ 'translation-key'}} for internationalization, the helper isn’t registered in your test setup. Try these solutions:
Load the i18n package in tests
Ensure your test command includes all necessary packages. If you’re usingmeteor test, it should loadtap:i18nautomatically, but double-check withmeteor listto confirm the package is installed.Mock the i18n helper
If you don’t want to spin up the full i18n system for tests, register a mock helper before rendering:beforeEach(() => { Template.registerHelper('_', (key) => { return key; // Return the key itself, or a custom mock translation }); });This lets your template render without throwing errors, and you can assert against the mock output.
Quick Troubleshooting Tip
First, check your template code to see exactly how _ is being used. If it’s in a loop like {{#each _.keys(items)}}, it’s Underscore. If it’s {{_ 'welcome-message'}}, it’s almost certainly an i18n helper. Knowing which one you’re dealing with will save you time!
Example Test Setup for Underscore
import { Blaze } from 'meteor/blaze'; import { Template } from 'meteor/templating'; import _ from 'underscore'; import './yourTemplate.html'; describe('Your Template', () => { let testDiv; beforeEach(() => { testDiv = document.createElement('div'); global._ = _; // Make Underscore available globally }); afterEach(() => { Blaze.remove(testDiv); }); it('renders without errors', () => { Blaze.renderWithData(Template.yourTemplate, { items: { a: 1, b: 2 } }, testDiv); // Add your assertions here, e.g., check if items are rendered correctly }); });
内容的提问来源于stack exchange,提问作者Saransh Dev Singh

