【问题标题】:How can I do Jest API test for this code?如何对此代码进行 Jest API 测试?
【发布时间】:2018-08-23 06:39:19
【问题描述】:

我已经尝试了几种方法来模拟我的代码单元,但它仍然不起作用。我正在使用 create-react-app 和 jest 进行测试。

我在管理员 adminSignup.js 中有一个功能,用于将数据发送到我的服务器(Node.js 和 Mongoose)以创建帐户:

/* eslint-disable no-undef */
 function signup(user, cb) {
 return fetch(`signup`, {
  headers: {"Content-Type": "application/json"},
  method: "POST",
  body:JSON.stringify({
    username: user.username,
    email: user.email,
    password: user.password,
    picode: user.pincode,
    building: user.building,
    city: user.city,
    state: user.state
        }),
})
  .then(checkStatus)
  .then(parseJSON)
  .then(cb)
  .catch(err => console.log(err));
}

function checkStatus(response) {
 if (response.status >= 200 && response.status < 300) {
  return response;
}
const error = new Error(`HTTP Error ${response.statusText}`);
error.status = response.statusText;
error.response = response;
console.log(error); // eslint-disable-line no-console
throw error;
}

function parseJSON(response) {
return response.json();
}

const adminSignup = { signup };
export default adminSignup;

我在我的组件中调用了它(RegisterPage.jsx):

adminSignup.signup( user, response => {
                         this.setState({response: response});
                         console.log(response);
                   });

现在我想为我的注册调用编写一个模拟 (adminSignup.js)。但只是想知道我该怎么做?

我已经尝试 Jest Fetch Mock 进行模拟测试(它不需要创建模拟文件)并且它正在工作,但我不太确定它是否正确:

describe('testing api', () => {
beforeEach(() => {
  fetch.resetMocks();
});

it('calls signup and returns message to me', () => {
  expect.assertions(1);
  fetch.mockResponseOnce(JSON.stringify('Account Created Successfully,Please Check Your Email For Account Confirmation.' ));

  //assert on the response
  adminSignup.signup({
    "email" : "sample@yahoo.com",
    "password" : "$2a$0yuImLGh1NIoJoRe8VKmoRkLbuH8SU6o2a",
    "username" : "username",
    "pincode" : "1",
    "city" : "Sydney",
    "building" : "1",
    "state" : "NSW"
}).then(res => {
    expect(res).toEqual('Account Created Successfully,Please Check Your Email For Account Confirmation.');
  });

  //assert on the times called and arguments given to fetch
  expect(fetch.mock.calls.length).toEqual(1);
});
});

我真的很喜欢创建一个模拟文件并用它进行测试,但是阅读 jest 网站对我不起作用。

提前致谢。

【问题讨论】:

    标签: javascript reactjs unit-testing mocking jestjs


    【解决方案1】:

    我为另一个 POST 请求找到了这种方式(使用 mock-http-server),它对我有用:

    userList.js:

    async function getUser (id, cb) {
    
    const response =  await fetch(`/getUserById/${id}`, {
      // headers: {"Content-Type": "application/json"},
      method: "POST",
      body:JSON.stringify({
        id : id
            }),
    })
       .then(checkStatus)
       .then(parseJSON)
       .then(cb)
       .catch(err => console.log(err));
    
    const user = response.json();
    return user;
    
     function checkStatus(response) {
       if (response.status >= 200 && response.status < 300) {
         return response;
       }
       const error = new Error(`HTTP Error ${response.statusText}`);
       error.status = response.statusText;
       error.response = response;
       console.log(error); // eslint-disable-line no-console
       throw error;
     }
    
     function parseJSON(response) {
       return response.json();
     }
    }
    

    userList.test.js:

    import ServerMock from "mock-http-server";
    import userLists from '../components/UserList/userLists';
    
    describe('Test with mock-http-server', function() {
    
    // Run an HTTP server on localhost:3000
    var server = new ServerMock({ host: "localhost", port: 3000 });
    
    beforeEach(function(done) {
      server.start(done);
    });
    
    afterEach(function(done) {
      server.stop(done);
    });
    
    it('should do something',  function(done) {
      var id = 4;
        server.on({
          method: 'POST',
          path: `/getUserById/${id}`,
          reply: {
              status:  200,
              headers: { "content-type": "application/json" },
              body:    JSON.stringify({ id: 4 })
          }
      });
      // Now the server mock will handle a GET http://localhost:3000//getUserById/${id}
      // and will reply with 200 `{"id": 4}`
      function cb(data) {
              console.log(data);
              expect(data).toBe({name:'Bob'}); 
              done();
          }
      const response =  userLists.getUser(4, cb);
      console.log(response);
    
    
      done();
    });
    

    【讨论】:

      猜你喜欢
      • 2021-07-21
      • 2021-11-06
      • 2020-08-17
      • 2022-01-14
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      相关资源
      最近更新 更多