我们如何断言HTML中嵌入的javascript变量在使用电子构建的应用程序中具有一些预期价值?目前的测试框架是spectron,mocha,chai,chai.should()和chai.use(chaiAsPromised)。
我想断言全局变量foo
的值为'foo'
。当我尝试foo.should.equal('foo')
时,我得到了ReferenceError: foo is not defined at Context.<anonymous> (test\spec.js:63:28)
下面是一个重新设计的spec.js.
const Application = require('spectron').Application
const assert = require('assert')
const electronPath = require('electron') // Require Electron from the binaries included in node_modules.
const path = require('path')
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const should = require('chai').should();
describe('Isolated testbeds house independent suites of tests.', function() {
this.timeout(30000);
before(function() {
this.app = new Application({
path: electronPath,
// directory structure:
// |__ myProject
// |__ ...
// |__ main.js
// |__ package.json
// |__ index.html
// |__ ...
// |__ test
// |__ spec.js <- You are here! ~ Well you should be.
args: [path.join(__dirname, '..')]
})
return this.app.start()
});
after(function() {
if (this.app && this.app.isRunning()) {
return this.app.stop()
}
});
/* BELOW IS THE TEST IN QUESTION */
it('should have a given value', function() {
return Promise.resolve(foo).should.eventually.equal('foo'); // HERE IS THE LINE IN QUESTION
});
})
Spectron“远程控制”您的Electron应用程序,并且不在同一名称空间中。这就是为什么在测试脚本中没有定义foo
的原因。
如果foo
在你的Electron前端,你可以使用this.app.client
访问它,如果它在DOM中。 this.app.browserWindow
或this.app.webContents
可能能够访问全局?
(我知道executeJavaScript()
不起作用 - 任何返回承诺的函数,基本上都不会起作用。)
如果foo
在你的后端,我在我的问题中显示了一个解决方法:Can Spectron call a function in back-end directly?(但我仍在寻找一种方法,不需要我修改代码来测试)