Mock data for ThinkJS3.
think-mock need Babel support! For:
- @babel/plugin-proposal-class-properties
- @babel/plugin-proposal-decorators
is used!Replace them with corresponding plugin if babel6 is used in your project!
- Open Babel transform (Both development or production enviroment)
- Add plugin to babel config
- Add extend support
// think.ROOT_PATH/src/config/extend.js
const mock = require('think-mock');
module.exports = [
mock(think.app),
];
- Config mock path, or use default
// config.js
mock: path.join(think.ROOT_PATH, 'mock'), // default
- Create mock file
// think.ROOT_PATH/mock/user/index.js
module.exports = {
mock: 'This is mock data.'
}
- Add mock to action or method
// controller/user.js
const { mock } = think.Controller.prototype;
module.exports = class extends think.Controller {
@mock
indexAction() {
// mockFile think.ROOT_PATH/mock/user/index.js
return this.json({ data: 'This is real data.' });
}
@mock getUserInfo() {
// mockFile think.ROOT_PATH/mock/user/getUserInfo.js
}
}
// service/sms.js
const { mock } = think.Service.prototype;
module.exports = class extends think.Service {
@mock
sendMessage() {
// mockFile think.ROOT_PATH/mock/service/sms/sendMessage.js
return { data: 'This is real data.' };
}
};
Mock auto close when you are not at devlepment enviroment.
You don't need remove decorator mock
, but is better if you do.