我正在编写一些测试来测试 Backbone View 及其模型之间的连接。我本质上想用模型加载我的 View ,并确保一切都是完美的(事件正确触发/处理,元素添加到 DOM 等)。我认为这与验收/功能/e2e 测试不同,但比简单的单元测试更大。换句话说,我不想写:
var browser = new Browser()
, fakeData = readFixtures("persons.json");
fakeAPIResponse('/persons', fakeData);
browser.visit("http://localhost:3000/", function () {
assert.ok(browser.success);
var persons = browser.queryAll(".persons li");
assert.lengthOf(persons, 20);
});
而是类似
var router = require('routers/main'),
UserModel = require('models/user'),
AccountView = require('views/account');
...
# In a test
var model = new UserModel({ userId: 1 });
router._showView(new AccountView({ model: model });
expect(document.getElementsByClassName('account-panel')).to.have.length(1);
model.set('name', 'Test Testerson');
expect(document.getElementById('name-field').value).to.equal('Test Testerson');
也许我还很遥远,应该将一些端到端测试放在一起,但在我看来,这将是一种有值(value)的测试方式。我的问题是:我怎样才能做到这一点?我需要一个完整的 DOM,所以我认为这些应该在 PhantomJS 之类的东西中运行; DOM 应该在每次测试之前重置,但让浏览器为每个单独的测试导航到新页面似乎很愚蠢/低效。有没有一个框架可以以这种方式运行测试?请随意告诉我,我想要这个是错误的。
最佳答案
我们正在使用 casperJs 来完成此操作。 Casper 将为您提供完整的 DOM,但这不应该成为选择集成测试而不是单元测试的原因。当我发现自己在创建测试环境方面付出了很大的努力时,我倾向于选择集成。
不过,话虽如此,我认为您可以进行单元测试,这就是我的做法。我们使用 testem 和 chaiJs 断言来进行此类测试。如果您设置了一个固定装置,您可以执行类似的操作(并且您将拥有完整的 DOM,并且能够测试事件以及 OP 中列出的其他所有内容)。
beforeEach(function () {
var theModel = new Backbone.Model(),
theViewToTest = new TheViewToTest({
model: theModel,
el: $(fixtures.get('some-fixture.html'))
});
theViewToTest.render();
this.theViewToTest = theViewToTest;
});
describe('Checking event handlers', function () {
it('Should fire some events', function () {
// I would setup a spy here and listen to the button handler
this.theViewToTest.$el.find('.some-button').trigger('click');
// Assert the spy was called once
});
});
关于javascript - 组件/集成测试主干 View 等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32540229/