我有一个在 Sails.js MVC 框架上运行的 Node.js 应用程序。该应用程序支持来自多个客户端的实时连接。它支持不同的角色。例如,您可以以标准用户或主持人身份登录。
为了进行测试,我使用 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
就应该出现在主持人的 View 以及标准用户的 View 上。
现在,测试单客户端方面效果很好。这是一个基本场景:
测试/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
不仅应该出现在主持人的 View 上,还应该出现在标准用户的 View 上。据我了解, mocha-phantomjs 模块将调用 casper.run()
方法,该方法启动源代码中前面定义的测试。所以这样的事情是行不通的:
测试/多客户端.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 实例,我可以为其编写例程。但是,这会导致错误:找不到模块“casper”
,因为 mocha-casperjs 框架不支持包含另一个 casperjs 实例。
永久注销并再次登录不是一个选项,因为我想测试应用程序的实时方面。
有人对如何在使用 mocha-casperjs 时实现 casperjs 的多个实例有建议吗?
最佳答案
在任何框架中您都会遇到问题,因为您需要两组 cookie,基本上是两个正在运行的浏览器。即使您确实创建了两个 casper 实例,您仍然处于共享 cookie 的一个 phantomjs 进程中。
可以做的是创建一个新的 WebPage 实例并将其交换到当前的 casper 实例上,并交换 cookie:
casper
.start('http://localhost:1337')
.logInAsMod()
.thenClick('button')
.then(function() {
('div.container').should.be.inDOM.and.visible;
})
.then(function() {
var userPage = require('webpage').create(),
modCookies = phantom.cookies
phantom.clearCookies()
casper
.logInAsUser()
.then(function() {
('div.container').should.be.inDOM.and.visible;
})
})
关于javascript - 多客户端 Node.js 应用程序的 mocha-casperjs headless 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23613627/