【发布时间】:2014-05-12 15:57:06
【问题描述】:
我有一个在 Sails.js MVC 框架上运行的 node.js 应用程序。该应用程序支持实时使用 socket.io 来自多个客户端的连接。它支持不同的角色。例如,您可以作为标准用户或版主登录。
对于测试,我使用 mocha-casperjs(以及 chai 和其他对我的问题不重要的东西)并使用 grunt mocha_phantomjs 从 grunt 运行测试。测试在我的项目根文件夹中的 Gruntfile.js 文件中指定。它们是这样指定的:
Gruntfile.js:
mocha_casperjs: {
files: {
src: [
'test/single-client.js',
'test/multi-client.js',
]
}
}
这是我要验证的测试用例:一旦主持人单击特定按钮,div.container 应该同时出现在主持人的视图和标准用户的视图中。
现在,测试单客户端方面效果很好。这是一个基本场景:
测试/single-client.js:
describe('Clicking on a Button as a Moderator', function() {
it('results in div.container to appear on the Moderators view', function() {
casper
.start('http://localhost:1337')
.logInAsMod() //Note: This is pseudocode for submitting a login form
.thenClick('button')
.then(function() {
('div.container').should.be.inDOM.and.visible;
})
})
}
导致:
Clicking on a Button as a Moderator
✓ results in div.container to appear on the Moderator's view
但是,我在测试此测试用例的多客户端方面时遇到了困难:div.container 不仅应该出现在主持人的视图中,还应该出现在标准用户的视图中。据我了解,启动源代码中前面定义的测试的casper.run() 方法将由 mocha-phantomjs 模块调用。所以这样的事情是行不通的:
测试/多客户端.js:
describe('Clicking on a Button as a Moderator', function() {
it('results in div.container to appear on the Moderators view and on the standard users view', function() {
casper
.start('http://localhost:1337')
.logInAsMod() //Note: This is pseudocode for submitting a login form
.thenClick('button')
.then(function() {
('div.container').should.be.inDOM.and.visible;
})
casper
.logInAsUser() //Note: This is pseudocode for submitting a login form
.then(function() {
('div.container').should.be.inDOM.and.visible;
})
})
}
上面代码的问题是casper.run()调用只创建了一个casperjs实例。如果我能写出这样的东西,那就太好了:
var casperMod = require('casper').create();
var casperUser = require('casper').create();
casperMod
.start('http://localhost:1337')
.logInAsMod() //Note: This is pseudocode for submitting a login form
casperUser
.start('http://localhost:1337')
.logInAsUser() //Note: This is pseudocode for submitting a login form
casperMod
.thenClick('button')
.then(function() {
('div.container').should.be.inDOM.and.visible;
})
casperUser
.then(function() {
('div.container').should.be.inDOM.and.visible;
})
所以我会有两个可以编写例程的 casperjs 实例。但是,这会导致 Error: Cannot find module 'casper',因为 mocha-casperjs 框架不支持包含另一个 casperjs 实例。
永久注销并再次登录不是一种选择,因为我想测试应用程序的实时性。
有没有人对使用 mocha-casperjs 时如何实现多个 casperjs 实例有建议?
【问题讨论】:
-
这很奇怪,因为它看起来不像 mocha-casperjs 内部使用了只允许一个实例的 casperjs 测试命令/环境。
-
您能具体说明您的意思吗?因为在我的测试例程中我自己不调用 casper.run(),所以我假设 mocha-casperjs 模块会这样做,这使得很难“注入”第二个将调用 run() 的 casper 实例。
-
我搜索了一下 mocha-casperjs 的源代码,并没有发现任何证据表明使用了
casperjs test。所以你应该能够使用第二个 casperjs 实例。第一个将由 mocha-casperjs 注入,第二个由您创建。casper.test对象在两个实例之间可能会有所不同。然后,您可能需要通过手动检查 contitions 从第二个实例中获取所需的(断言)信息,而不使用来自 2. 实例的casper.test。然后,您可以在 1. 实例上调用test.pass或test.fail。 -
我既没有 grunt 也没有 mocha-casperjs 设置,所以我无法验证。因为我不确定,所以我不会写答案。
-
谢谢你,我会尝试这些东西,一旦找到合理的方法,我会在这里回复。
标签: javascript node.js unit-testing phantomjs sails.js