我有一个在API控制器中正在调用的函数,该函数从类中调用继承的属性。如何模拟此继承的属性以使其运行其行为,但不一定连接到进行初始化的网络/数据库? 我曾尝试使用嘲讽,但它并没有表现出我期望的样子。
P.S。我问这是因为我还不知道如何使用sinon-chai创建测试脚本。
这是我到目前为止尝试过的:
//test-process.js
const sinon = require('sinon');
const chai = require('chai');
const expect = chai.expect;
const should = chai.should();
const mockery = require('mockery');
chai.use(require('chai-as-promised'));
const obj = require('./data/test-process-data');
let sandbox,req;
describe('Test process controller') ()=>{
beforeEach(()=>{
sandbox = sinon.createSandbox();
req ={
body: obj.body.data,
};
const mockingFunc = require('./callFunc');
mockery.registerMock('./callFunc', mockingFunc);
sinon.mock(mockingFunc, 'getDefaultFunc');
})
afterEach(() => {
sandbox.restore();
})
describe('Test Create Transaction', () => {
it('should create new transaction', async () => {
const res = await chai.request(url).post('/api/process').send(req.body);
should.exist(res.body);
res.body.should.be.a('object');
res.should.have.status(200);
res.body.should.have.property('message').eql('Successfully saved transaction Data.');
done();
});
});
}
这是我的功能和控制器代码:
//mymainfunc.js
const processFunc = require('processFunc');
class mainFunc{
constructor(name,address,phoneNumber){
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
}
init(options){
this.conOptions = options;
}
async processData(funcName,params){
const runProcess = await processFunc.createTransaction(funcName,params);
return runProcess;
}
}
module.exports = mainFunc;
//callFunc.js
const mainFunc = require('mymainfunc');
const callFunc = {};
let defaultFunc;
const fullname="Alix";
const address = "Colorado";
const contactNumber = "303-555-01234";
//this is being called in server.js
callFunc.init() = async (dbConfig,netConfig){
try{
....
defaultFunc = new mainFunc(fullname,address,contactNumber);
defaultFunc.init(netConfig);
}catch(err){
throw new Error('process error: ' + err);
}
}
callFunc.getDefaultFunc = () => {
return defaultFunc;
};
module.exports = callFunc;
//process api controller
const callFunc = require('./callFunc');
const process = {};
process.create= asyc(req,res){
const transactionData= {
orderId: req.body.orderId,
items:req.body.items
}
try{
const submitData = await callFunc.getDefaultFunc().processData('createTransaction',transactionData);
res.json({ statusCode: 200, success: true, data: JSON.parse(submitData.toString())});
}catch(err){
res.json({ statusCode: 500, data: {}, message: "Transaction Error!" });
}
};
module.exports = process;