SinonJS 间谍无法恢复对象的只读 Method/Property
SinonJS Spy Cannot Restore Read Only Method/Property of Object
它给了我 TypeError: Cannot assign to read only property 'get' of object '#<Config>'
.
我正在使用 mocha 8.0.1
、chai 4.2.0
、sinon 9.0.2
进行单元测试。
我正在监视 config npm 包中的一个方法。
以下是我侦测 get
方法的方法:
...
before(() => {
sandbox = sinon.createSandbox();
configStub = sandbox.spy(config, 'get');
});
after(() => {
sandbox.restore();
});
it('should something', async () => {
console.log('Just logging');
config.get('LOG.LEVEL'); // just to show the point. if I remove this line, it doesn't throw the error
});
...
发生的情况是,如果我在测试期间某处运行 config
的get
方法,它无法被间谍恢复。它抛出只读 属性 错误。但是当从未调用 config.get
函数时,它不会抛出该错误(我不明白为什么不抛出)。对于stub
没问题,可以恢复就好了。
但我使用 spy
的原因是因为我希望 config.get
在我测试正在使用它的 module/function 时像往常一样工作,我只想监视它。而且我还需要能够在这个测试套件之后恢复它。我监视它是因为我需要测试它是否被我的 module/function 使用一些特定参数调用。
如何监视 只读 property/method,让我的 module/function 像往常一样使用它,然后恢复它?
谢谢:)
您可以将 ALLOW_CONFIG_MUTATIONS
环境变量设置为 true
以进行测试 运行。
这样 config.get
调用不会冻结应该解决问题的配置。
您可以在文档中找到环境变量描述:
https://github.com/lorenwest/node-config/wiki/Environment-Variables#allow_config_mutations
它给了我 TypeError: Cannot assign to read only property 'get' of object '#<Config>'
.
我正在使用 mocha 8.0.1
、chai 4.2.0
、sinon 9.0.2
进行单元测试。
我正在监视 config npm 包中的一个方法。
以下是我侦测 get
方法的方法:
...
before(() => {
sandbox = sinon.createSandbox();
configStub = sandbox.spy(config, 'get');
});
after(() => {
sandbox.restore();
});
it('should something', async () => {
console.log('Just logging');
config.get('LOG.LEVEL'); // just to show the point. if I remove this line, it doesn't throw the error
});
...
发生的情况是,如果我在测试期间某处运行 config
的get
方法,它无法被间谍恢复。它抛出只读 属性 错误。但是当从未调用 config.get
函数时,它不会抛出该错误(我不明白为什么不抛出)。对于stub
没问题,可以恢复就好了。
但我使用 spy
的原因是因为我希望 config.get
在我测试正在使用它的 module/function 时像往常一样工作,我只想监视它。而且我还需要能够在这个测试套件之后恢复它。我监视它是因为我需要测试它是否被我的 module/function 使用一些特定参数调用。
如何监视 只读 property/method,让我的 module/function 像往常一样使用它,然后恢复它?
谢谢:)
您可以将 ALLOW_CONFIG_MUTATIONS
环境变量设置为 true
以进行测试 运行。
这样 config.get
调用不会冻结应该解决问题的配置。
您可以在文档中找到环境变量描述:
https://github.com/lorenwest/node-config/wiki/Environment-Variables#allow_config_mutations