尝试使用mockingoose模拟静态mongoose函数(getLoginData)但没有运气。
有没有人有我的工作示例?这是我得到的:
我的用户模型 // models / user.js
...
UserSchema.methods.login = function (username, password, host) {
Game.setHost(host);
this.setUserData(username, password);
return this.constructor.getLoginData().then(loginPageData => {
const loginData = Object.assign({}, defaultLoginData, {
name: this.username,
password: this.password,
login: loginPageData.loginInput
});
return this.constructor.loginWithUserData(loginData);
}).catch(error => console.log(error))
};
UserSchema.statics.getLoginData = function () {
const options = {
url: Game.getUrl(config.LOGIN),
};
return request(options, pages.getLoginPageData);
};
我的单元测试 // 测试 /user.js
...
describe('User', () => {
describe('login', function () {
it('username and password should set as virtual', () => {
const user = new User({});
mockingoose.User.toReturn(
Promise.resolve(responseMocks.loginPage), 'getLoginData'
);
mockingoose.User.toReturn(
expectedLoginData,
'loginWithUserData'
);
user.login('foo', 'bar').then(loginData => {
expect(user.username).to.equal(expectedLoginData.name);
});
})
});
});
答案 0 :(得分:0)
好的,解决方案非常简单。我只是直接模拟模型的静态:
...
describe('User', () => {
describe('login', function () {
it('username and password should set as virtual', () => {
User.getLoginData = jest.fn(() =>
Promise.resolve(responseMocks.loginPage));
User.loginWithUserData = jest.fn(() => expectedLoginData);
const user = new User({});
user.login('foo', 'bar').then(loginData => {
expect(user.username).to.equal(expectedLoginData.name);
});
})
});
});