使用Jest测试调用PHP ajax的Jquery

时间:2018-02-05 20:19:53

标签: javascript php jquery ajax jestjs

我有一个Javascript文件,其中包含我正在尝试测试的函数。所有函数都是对PHP ajax文件发出jQuery post请求(参见代码)

function loadTeams(clubID){

var data = {
    action: 'loadClubTeams',
    clubID: clubID
};

return jQuery.post('/ajax/calendar_ajax.php', data);
}

我在我的/__mocks__/目录中设置了一个模拟器:

<?php

$teams = array(
    array(
        "Name" => "Team 1",
        "ClubID" => 34
    ),
    array(
        "Name" => "Team 2",
        "ClubID" => 34
    ),
    array(
        "Name" => "Team 3",
        "ClubID" => 35
    )
);
$response = array();
if($_REQUEST['action'] == "loadClubTeams"){
    foreach($teams as $team){
        if($team['ClubID'] == $_REQUEST['ClubID']){
            array_push($response, $team);
        }
    }
}
return json_encode($response);

这是我的测试文件:

const assoc_cal = require('../../secure-htdocs/js/templates/association_calendar');
jest.mock('../../secure-htdocs/ajax/calendar_ajax.php');

    test("loadTeams returns Teams 1 and 2 when passed clubID 34", () =>{
        data = {action: "loadTeams", ClubID: 34};
        const expected = [
            {
                name: "Team 1",
                clubID: 34
            },
            {
                name: "Team 2",
                clubID: 34
            }
        ];
        expect(assoc_cal(data)).toEqual(expect.arrayContaining(expected));
    });

但是当我运行我的测试时,它仍然试图调用真正的calendar_ajax.php文件。我显然错误地设置了模拟。其他人可以用这个吗?

0 个答案:

没有答案