我一直在为此苦苦挣扎。本质上,当我将它们的值记录到测试中的控制台时,存根似乎可以工作,但是当我使用存根模块方法向端点发出请求时,这些存根没有被使用,它们实际上正在与数据库进行交互。这是测试(添加了一些评论来解释问题):
it.only('Returns correct response', () => {
// if I do questionsSeen.add().then(res => console.log(res)) I see the value
// 30, but this function interacts with the db and when I make my POST
// request to '/api/quiz/finish' it's still interacting with it
cy.stub(questionsSeen, 'add').resolves(true);
cy.stub(questionsSeen, 'getCount').resolves(30);
// I reset db after every test, so I need to register a user and login
cy.request('POST', '/api/auth/register', {
email: 'john.doe@foo.com', password: 'securepass123', firstName: 'john', lastName: 'doe',
});
cy.request('POST', '/api/auth/login', {
email: 'john.doe@foo.com', password: 'securepass123',
});
// this is where I use the stubbed methods and they're still being called
// with their actual implementation
cy.request({
method: 'POST',
url: '/api/quiz/finish',
body: { questions, topic: 'foo', level: 1 },
}).then((response) => {
expect(response).to.have.property('headers');
expect(response).to.have.property('body');
expect(response.body).to.eq(2);
expect(response.status).to.eq(200);
});
});
我的/api/quiz/finish
路线仅使用questionsSeen方法,例如await questionsSeen();
。
基本上, 如我在上面的代码中所说,当我将其解析的值记录到测试文件中时,存根似乎可以工作,但是当我向实际上使用这些功能的'/ api / quiz / finish'请求时,它们仍在使用正确的实现并尝试访问db ec。 真正坚持这一点,任何帮助将不胜感激! 谢谢