我有以下模塊:注入存根依賴性成ES6類興農
const rp = require('request-promise');
// dummies.repository.js
exports.getDummiesData =() => {
const options = {
url: 'https://api.github.com/users',
headers: {
'User-Agent': 'Request-Promise',
},
json: true
};
return rp(options)
.then(r => r)
.catch(err => { throw err; });
}
上述文件是我想測試一類的依賴關係。我通過其構造它注入到下面的類,像這樣:
// dummies.service.js
const Dummies = require('./dummies.model');
class DummiesService {
constructor(dummiesRepository) {
this.dummiesRepository = dummiesRepository;
}
getDummies() {
return new Promise((resolve, reject) => {
this.dummiesRepository.getDummiesData()
.then((response) => {
// business logic
const dummies = response.map(d => new Dummies(d));
resolve(dummies);
})
.catch((response) => {
reject(response);
});
});
}
}
module.exports = DummiesService;
在上面,我想與興農測試方法getDummies
。到目前爲止,我的方法是在實例化過程中將dummiesRepository
殘缺並注入到我的傻瓜服務中,但是出現錯誤。下面是我測試的樣子:
const DummiesService = require('../dummies.service');
const dummiesRepository = require('../dummies.repository');
let dummiesRepositoryStub;
afterEach(() => {
if(dummiesRepositoryStub){
dummiesRepositoryStub.restore();
}
});
describe('unit: dummies.service - when getting dummies data',() => {
it('it should resolve and return dummies data',() => {
const dummiesResponse = [
{ id: 1, login: 'dummy1', additionalData: 'data' },
{ id: 2, login: 'dummy2', additionalData: 'data' },
{ id: 3, login: 'dummy3', additionalData: 'data' },
];
dummiesRepositoryStub = sinon
.stub(dummiesRepository, 'getDummiesData')
.resolves(dummiesResponse);
dummiesService = new DummiesService(dummiesRepositoryStub);
// act + assert
return dummiesService.getDummies()
.then((response) => {
chai.expect(dummiesRepositoryStub.called).to.equal(true);
chai.expect(response).to.deep.equal(dummiesTransformedModel);
});
});
此測試失敗,錯誤TypeError: this.dummiesRepository.getDummiesData is not a function
。我不知道爲什麼這不起作用,我將dummiesRepository的存根實現注入到DummiesService
類中。請協助。
第一行缺少單引號。 'const rp = require('request-promise);'應該是'const rp = require('request-promise');' – SteamDev
謝謝,但這不是我的錯誤。我只是錯過了這個問題 – strizzwald