关于使用egg.js的 单元测试 controller 如何添加header
发布于 6 年前 作者 cl1069573062 5927 次浏览 来自 问答

我想单元测试 token的验证代码 我把token放在header 的 Authorization中。 请问如何添加header。 我使用下面的方法是错误的

it.only('post /data', async () => {

    const result = await app.httpRequest()
        .post('/data')
        .header({
            Authorization: '11111',
        })
        .type('form')
        .send({ test: 'admin', test: 'root' });

    console.log(result.body);
});
7 回复

不太清楚 app是啥,如果要另辟蹊径的话,可以使用request模块或者http.request

@wangchaoduo 在测试用例里面使用 request 模块 。但是应用服务没有启动啊

可能 .header 接收 key、value 两个参数,而不是一个对象? 如果不是看看是不是跨域之类导致的没设置成功

@rrbe 没有直接显示 没有 header 这个 function

egg.js的单元测试用的是egg-mock,里面请求用的是superTest,而superTest网络请求用的是superAgent,添加header根据文档查到是SuperAgent.Setting header fields

BTW,我自己也是这样用的~

希望我这样写能帮助到你。

app.httpRequest() 就是一个 supertest 实例,看它文档就知道了。

app.httpRequest().get('/').set('xx', 'aaa')

        app.httpRequest()
          .get('/api/user/current')
          .set('authorization', `Bearer ${accessToken}`)
          .expect(res => {
            console.log(res);
          });

这样子可以的,但是,token怎么动态设置,总不能写死吧

回到顶部