在一个使用电子构建的应用程序中,我们如何断言嵌入在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
});
})发布于 2018-03-02 19:48:38
Spectron是“远程控制”你的电子应用程序,并且不在同一个命名空间中。这就是测试脚本中没有定义foo的原因。
如果foo在您的电子前端,您可以使用this.app.client访问它(如果它在DOM中)。this.app.browserWindow或this.app.webContents是否可以访问全局变量?
(我知道executeJavaScript()不会工作--任何返回promise的函数基本上都不会工作。)
如果foo在您的后端,我在我的问题中展示了一个解决方法:Can Spectron call a function in back-end directly? (但我仍然在寻找一种不需要修改代码即可进行测试的方法)。
https://stackoverflow.com/questions/49041558
复制相似问题