简体   繁体   English

快递:我不知道如何使用sinon

[英]Express: I don't understand how to use sinon

I have a controller with method: 我有一个控制器的方法:

registration(req, res) {
  if (!req.user) return res.status(401).send('Registration failed');

  const { user } = req;
  return res.status(201).json({ user });
},

I want to test the registration method which sends the json with my fake data. 我想测试使用我的假数据发送json的注册方法。

const { expect } = require('chai');
const sinon = require('sinon');
const authController = require(...);

describe('authController', () => {
  const USER = {
  email: 'test@test.com',
  password: 'Test12345',
  confirm: 'Test12345',
  username: 'Test',
};

it('it should send user data with email: test@test.com', () => {
  const req = { user: USER };
  const res = {
    status: sinon.stub().returnsThis(),
    json: sinon.spy(),
  };

  console.log('RES: ', res); // I can't see the json data
  authController.registration(req, res);
  expect(res.json).to.equal(USER);
});

I checked that my USER's data go into controller (req.user). 我检查了我的USER数据是否进入控制器(req.user)。 I tried to look what contains res with spy, but didn't find my USER data I don't understand how to use sinon in my situation? 我试图查看间谍中包含res的内容,但是找不到我不知道如何在我的情况下使用sinon的USER数据?

You almost made it with the test. 通过测试,您几乎做到了。 For this kind of test, we can use calledWith from Sinon to check functions and arguments being called properly. 对于这种测试,我们可以使用calledWith从兴农检查功能和参数被正确调用。

describe('authController', () => {
  const USER = {
    email: 'test@test.com',
    password: 'Test12345',
    confirm: 'Test12345',
    username: 'Test',
  };

  it('it should send user data with email: test@test.com', () => {
    const req = { user: USER };
    const res = {
      status: sinon.stub().returnsThis(),
      json: sinon.spy(),
    };

    authController.registration(req, res);

    // this is how we check that the res is being called with correct arguments
    expect(res.status.calledWith(201)).to.be.ok;
    expect(res.json.calledWith({ user: USER })).to.be.ok;
  });
});

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM