首页 文章

初始函数调用后运行Jasmine测试

提问于
浏览
3

我正在为Node.js API编写Jasmine测试 . 我正在尝试测试创建用户功能 . 测试看起来像这样:

describe('User test', function() {
  describe('Post /api/saveUser'), function() {
    it('saves a new user', function(done) {
      request.post({url: 'http://website/api/saveUser', form:{email:testU.email, password:testU.password}, headers: {'authorization': adminU.jwt}}, function(err, res, body) {
        expect(res.statusCode).toBe(200);
      });
    });
  });
});

因此,我需要在规范中对admin用户(adminU)进行身份验证,以获取有效令牌以传递请求 . 这是使用另一个 endpoints 完成的 .

request.post({url: 'http://website/api/authenticate', form:{email:adminU.email, password: adminU.password}}, function(err, res, body) {
  adminUser.jwt = JSON.parse(res.body).token;
});

但是我如何结合这些 . 如果我将验证代码插入用户测试块之上,则在收到来自验证 endpoints 的响应之前运行用户测试 . 显而易见的选择是将用户测试包装在来自authenticate api的回调中,但是当我运行测试时,Jasmine实际上并没有运行它们 .

在Jasmine规范中使用回调结果的最佳方法是什么?

1 回答

  • 0

    您需要等到auth呼叫的请求完成 .

    it('saves a new user', function(done) {
        request.post({
            url: 'http://website/api/authenticate',
            form: {
                email: adminU.email,
                password: adminU.password
            }
        }, function(err, res, body) {
            adminUser.jwt = JSON.parse(res.body).token;
            request.post({
                url: 'http://website/api/saveUser',
                form: {
                    email: testU.email,
                    password: testU.password
                },
                headers: {
                    'authorization': adminU.jwt
                }
            }, function(err, res, body) {
                expect(res.statusCode).toBe(200);
                done();
            });
        });
    });
    

    如果您需要多次测试中的令牌,我建议将其放在前块中 . 如果你这样做,jasmine在开始测试之前运行一次,你不必在每个测试用例中进行auth调用 .

    before(function(done){
        request.post({
            url: 'http://website/api/authenticate',
            form: {
                email: adminU.email,
                password: adminU.password
            }
        }, function(err, res, body) {
            if(err) done(err);
            adminUser.jwt = JSON.parse(res.body).token;
            done();
        });
    });
    

    此外,我建议supertest测试apis . 见https://www.npmjs.com/package/supertest

相关问题