最近写接口代码尝试用测试,用了一下,感觉还是很爽的,提前解决了很多 bug 。不过因为不太熟练,所以常常在解决 supertest 的问题,在这里总结一下。
登录测试
有些接口需要登录测试,而这些登录测试往往需要前后一致的 session ,这里我们可以通过取 cookie 解决。当然,如果是 token 直接取 token 就行了。
简单写一下就行了,举个例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const request = require('supertest'); const server = request.agent('http://localhost/'); describe('测试', () => { it('需要登录后测试', async done => { server .post('/login') .send({username: 'username', password: 'password'}); const res = server .get('/getList') .query({name: 'ddd'}); expect(res.status).toBe(200); done(); }); });
|
Expect 使用的经验
1 2 3 4 5 6 7 8
| expect(str).toBe('123'); expect({a: 1}).toStrictEqual({a : 1}); const mock = jest.fn(); mock(5); expect(mock).toBeCalledWith(expect.any(Number)); expect(mock).toBeCalledWith(expect.anything()); mock.mockRestore(); expect(true).toBeTruthy();
|
目前我常用的就是这一些了,以后有的话可以再补充。