【发布时间】:2020-12-09 13:28:43
【问题描述】:
好的,这是repo
我想做的事:测试我的受保护路由。
目前,应用程序的安全性由护照处理,采用以下策略:graphql-passport。
我正在用 supertest(针对请求)和玩笑来休息
当我构建 Apollo 服务器时,我使用它来创建上下文:
import { buildContext } from 'graphql-passport';
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req, res }) => {
return buildContext({ req, res, User })
},
playground: {
settings: {
'request.credentials': 'same-origin',
},
},
});
这允许我从请求中获取用户。就像任何使用护照的身份验证一样。
passport.use(
new GraphQLLocalStrategy((email, password, next) => {
console.log(`???? GraphQLLocalStrategy ${email} ???? ????♂`)
User.findOne({ email })
.then(user => !user
? next(null, false, 'Invalid email or password')
: user.checkPassword(password) //bcrypt
.then(match => !match
? next(null, false, 'Invalid email or password')
: next(null, user)
)
)
.catch(error => next(error))
}),
);
到目前为止,它运行良好。对于我运行的每个测试,我都可以看到我的???? GraphQLLocalStrategy ${email} ???? ????♂ 被调用。好!。
对于某些突变,例如登录和更新用户配置文件,我可以这样做: user.mutations.test.js
// * Login for add the user in the context
agent
.post("/graphql")
.send({ query: ` mutation {
${loginQuery(email)}
${updateFirstName}
}`})
.set("Accept", "application/json")
.end((err, {body:{data, errors}}) => {
if (err) return done(err);
const {updateUser} = data;
expect(updateUser).toBeInstanceOf(Object);
expect(updateUser.email).toBe(email);
expect(updateUser.firstName).toBe(newName);
expect(updateUser.rol).toBe("patron");
UserFields.map(checkFields(updateUser));
done();
})
因此,在一个查询中,我可以发送登录突变,然后运行更新名字突变。两者都足够好用,根据护照我已登录,我可以更新用户个人资料。
有什么问题?我想运行一个日志记录mutation,然后运行一个查询来获取所有用户。 p>
但是,当然,我不能在 request(app).post("/graphql").send() 中同时运行两者。它必须是一个或多个突变或查询......但不能同时运行。
另一个想法,谁不工作,运行一个,并在响应中运行第二个,像这样:
const agent = request(app);
agent
.post("/graphql")
.send({ query: `mutation { ${loginQuery(email)} }`})
.end((err, {body:{data}}) => {
if (err) return done(err);
agent
.post("/graphql")
.send({ query: `query { getGuestsQuery() }`})
...
如果我尝试在第二个请求中请求受保护的路由,则无法知道我已通过身份验证,至少不会自动... 我可以在这里使用 supertest 发出经过身份验证的请求强>
**如何告诉我测试的应用程序我已通过身份验证???? **
【问题讨论】:
标签: graphql passport.js apollo-server supertest