如何测试用玩笑来操纵DOM的普通js代码

时间:2018-11-28 08:18:20

标签: javascript unit-testing async-await mocking jestjs

// get submit button and add event listener to it
const submitBtn = document.getElementById("submit");
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
            document.getElementById("notify").innerHTML =`<div class="isa_success">
                               <i class="fa fa-check"></i>
     ${response.Message}
    </div>`;
        window.location.assign('../HTML/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.js文件,它监听提交按钮,然后执行访存操作来登录用户。

下面是我的login.test.js文件。.这是对login.js的测试,但无法正常工作。我尝试将await Promise.resolve.then()更改为jest.UseFakeTimers(),但是它不起作用。任何人都知道为什么它不起作用,以及可能的解决方案?

describe('login',() => {
    let fetchMock;
    let assignMock;

    beforeEach(() => {
        document.body.innerHTML +=`
        <div id="notify">
          </div>
        <form id="signin">
          <input type="email" id="email" value="test@gmail.com">
          <input type="password"  id="password" value ="test1234">
          <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 function() {
        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",
            headers: {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin':'*',
                'Access-Control-Request-Method': '*'
            },
            mode: "cors",
            body: JSON.stringify({
                email: 'test@gmail.com',
                password: "test1234"
            })

        });
     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("../HTML/index.html");
    });


});

这是我得到的错误:

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: "
          "

Difference:

- Expected
+ Received

- <div class="isa_success">
- <i class="fa fa-check"></i>
-     User logged in successfully!
-      </div>
+ 
+            <Click to see difference>


      45 |         });
      46 |      await Promise.resolve().then();
    > 47 |      expect(document.getElementById('notify').innerHTML).toBe(`<div class="isa_success">
         |                                                          ^
      48 | <i class="fa fa-check"></i>
      49 |     User logged in successfully!
      50 |      </div>`);

      at Object.toBe (__tests__/login.test.js:47:58)
      at tryCatch (node_modules/regenerator-runtime/runtime.js:62:40)
      at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:296:22)
      at Generator.prototype.(anonymous function) [as next] (node_modules/regenerator-runtime/runtime.js:114:21)
      at step (__tests__/login.test.js:3:191)
      at __tests__/login.test.js:3:361

1 个答案:

答案 0 :(得分:0)

解决方案非常简单。我只需要添加await Promise.resolve.then()行即可使其工作:

    describe('login',() => {
        let fetchMock;
        let assignMock;

        beforeEach(() => {
            document.body.innerHTML +=`
            <div id="notify">
              </div>
            <form id="signin">
              <input type="email" id="email" value="test@gmail.com">
              <input type="password"  id="password" value ="test1234">
              <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 function() {
            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",
                headers: {
                    'Content-Type': 'application/json',
                    'Access-Control-Allow-Origin':'*',
                    'Access-Control-Request-Method': '*'
                },
                mode: "cors",
                body: JSON.stringify({
                    email: 'test@gmail.com',
                    password: "test1234"
                })

            });
         await Promise.resolve().then();
         await Promise.resolve().then(); //on adding this the test passes
         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("../HTML/index.html");
        });


});