这是我的login.js文件,我在其中登录用户并生成令牌。我添加了注释以使代码更具可读性。
// get submit button and add event listener to it
const submitbtn = document.getElementById("submit");
console.log(submitbtn.value);
if(submitbtn){
submitbtn.addEventListener('click', loginFunction)
}
//call back function
function loginFunction(e){
e.preventDefault();
// the data to post
const data = {
email: document.getElementById("email").value,
password: document.getElementById("password").value,
};
// post the data to db via fetch
fetch("https://store-manager-api-app-v2.herokuapp.com/api/v2/auth/login",{
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin':'*',
'Access-Control-Request-Method': '*'
},
method:"POST",
mode: "cors",
body: JSON.stringify(data)
}).then(function(response){return response.json()})
.then(function(response){
localStorage.setItem('token', response.token);
if (response.Message === "User logged in successfully!"){
// redirect to index page
console.log(response.Message);
document.getElementById("notify").innerHTML =`<div class="isa_success">
<i class="fa fa-check"></i>
${response.Message}
</div>`;
console.log(document.getElementById('notify').innerHTML);
window.location.assign('./index.html')
}
else{
let notify = document.getElementById("notify");
notify.innerHTML =`<div class="isa_info">
<i class="fa fa-info-circle"></i>
${response.Message}
</div>`
}
})
}
因此,我为此文件编写了一个测试,名为login.test.js。这是代码
describe('login',() => {
let fetchMock;
let assignMock;
beforeEach(() => {
document.body.innerHTML +=`
<div id="notify"></div>
<form id="login">
<input type="email" id="email" value="test@gmail.com">
<input type="password" id="password" value ="testgmail1234">
<input type="submit" id="submit">
</form>`;
fetchMock = jest.spyOn(global, 'fetch');
fetchMock.mockImplementation(() =>Promise.resolve ({
json: () => Promise.resolve({Message:"User logged in successfully!"})
}));
assignMock = jest.spyOn(window.location , "assign");
assignMock.mockImplementation(() =>{});
require('../UI/js/login');
});
afterEach(() => {
fetchMock.mockRestore();
assignMock.mockRestore();
jest.resetModules()
});
it('fetch data and change the content of #notify', async () =>{
document.getElementById('submit').click();
expect(fetchMock).toHaveBeenCalledTimes(1);
const fetchArgs = fetchMock.mock.calls[0];
expect(fetchArgs[0]).toBe('https://store-manager-api-app-v2.herokuapp.com/api/v2/auth/login');
expect(fetchArgs[1]).toEqual({
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/json",
'Access-Control-Allow-Origin':'*',
'Access-Control-Request-Method': '*'
},
body: JSON.stringify({
email: 'test@gmail.com',
password: "testgmail1234"
})
});
await Promise.resolve().then();
expect(document.getElementById('notify').innerHTML).toBe(
`<div class="isa_success">
<i class="fa fa-check"></i>
User logged in successfully!
</div>`);
expect(assignMock).toHaveBeenCalledTimes(1);
expect(assignMock.mock.calls[0][0]).toBe("./index.html");
});
it('Login with wrong email/password', async () =>{
fetchMock = jest.spyOn(global,'fetch');
fetchMock.mockImplementation(() =>Promise.resolve ({
json: () => Promise.resolve({message:"User not found!"})
}));
document.getElementById('submit').click();
expect(fetchMock).toHaveBeenCalledTimes(1);
const fetchArgs = fetchMock.mock.calls[0];
expect(fetchArgs[0]).toBe('https://store-manager-api-app-v2.herokuapp.com/api/v2/auth/login');
await Promise.resolve().then();
expect(document.getElementById('notify').innerHTML).toBe( '<div class="isa_info">\n ' +
' <i class="fa fa-info-circle"></i>\n ' +
'User not found!\n' +
'</div>');
});
});
当我运行此代码时,它因以下错误而失败:
Error: expect(received).toBe(expected) // Object.is equality
Expected: "<div class=\"isa_success\">
<i class=\"fa fa-check\"></i>
User logged in successfully!
</div>"
Received: "" <Click to see difference>
46 | console.log(Promise.resolve().then());
47 | console.log(Promise.resolve().then());
> 48 | expect(document.getElementById('notify').innerHTML).toBe(
| ^
49 | `<div class="isa_success">
50 | <i class="fa fa-check"></i>
51 | User logged in successfully!
我一直在尝试找出可能的问题,但未成功。有人可以帮忙吗?我使用笑话作为我的测试跑步者。