我刚接触单元测试和间谍、存根和模拟的概念。
我想要测试下面代码中的password.js
文件中的verify
方法,但是我无法在测试文件中stub
函数hash
。
verify
使用hash
函数,而hash
函数被导出,因此我认为我应该stub
hash
函数来返回一个固定的响应,而不是实际调用hash
。因为我不是在尝试测试hash
函数。
问题:hash
函数的创建存根在测试verify
时未被调用。
补充问题1:我应该关注测试函数本身的逻辑而不是其他调用的函数吗?
主要问题:(已回答)如何stub同一模块中调用的模块函数?
补充问题2:如果hash
函数没有被导出,而只留在模块中,我应该如何存根hash
?
代码
password.js
/**
* Creates a hash based on a salt from a given password
* if there is no salt a new salt will be generated
*
* @param {String} password
* @param {String} [salt] Optional value, if not given will generate a salt
*/
function hash (password, salt) {
// returns a promise that resolves an hash object with hash and salt key
// example: {hash: '2512521nska...', salt: '25hbBhhsfa...'}
}
/**
* Verifies if a password matches a hash by hashing the password
* with a given salt
*
* @param {String} password
* @param {String} hashString
* @param {String} salt
*/
function verify (password, hashString, salt) {
return hash(password, salt)
.then((res) => res.hash === hashString);
}
module.exports = {hash, verify};
password.test.js
import test from 'ava';
import sinon from 'sinon';
import passwordModule from './password';
test('verify - should verify password', function * (t) {
const password = 'test-password';
const salt = null;
const hash = 'my-hash';
const hashStub = sinon.stub(passwordModule, 'hash', (password, salt) => Promise.resolve({hash, salt}));
const verified = yield passwordModule.verify(password, hash, salt);
t.true(verified);
hashStub.restore();
});
设置
- Node版本为v6.2.0
- Ava版本为v0.15.2
- Sinon版本为v1.17.4
测试和模块都使用babel进行转换。但是该模块没有使用ES6模块导出,因为它在node环境中使用时不需要进行转换。
我在测试期间对所有代码进行了转换,以便使其具有未来的兼容性,并且可以同时用于前端和后端代码,其中前端代码也经过了转换。
hash
可能有点多余 :) - robertklep