我已经尝试了几种方法来嘲笑我的代码的这个单元,但仍然不起作用。我使用create react app和jest进行测试。
我在行政部有一个职能
管理员注册.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;
我在我的组件中称之为(
) :
adminSignup.signup( user, response => {
this.setState({response: response});
console.log(response);
});
现在我想为我的注册电话写一个模拟(
). 但我想知道我怎么做?
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网站对我来说并不管用。
提前谢谢。