Home > Enterprise >  How to load up the whole Django project (including js files) when testing with webdriver in Selenium
How to load up the whole Django project (including js files) when testing with webdriver in Selenium

Time:01-16

I am using Selenium to test my Django project's JavaScript.

The web driver is getting the index.html which is the home page but the JavaScript is not loading up in my index.html page (as if I were running the whole project, not individual page/template).

How do I load up the whole Django project for the web driver to get the intended result?

I ran the test file and got the following error:

"self.assertEqual(driver.find_element(By.ID, "cash-table-usd").text, 100) AssertionError: '{{ usd|intcomma }}' != 100"

{{ usd|intcomma }} is templated as I believe other files in my Django project is not loading up.

I was expecting it to be 0 initially, then becomes 100 after the click button in the test.

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By

def file_uri(filename):
    return pathlib.Path(os.path.abspath(filename)).as_uri()

driver = webdriver.Chrome(ChromeDriverManager().install())

class ClientSideTests(unittest.TestCase):

    def test_deposit_withdraw(self):
        driver.get(file_uri("portfolio/templates/portfolio/index.html"))
        balance = driver.find_element(By.ID, "cash-table-usd").text
        driver.find_element(By.ID, "cash-amount").send_keys(100)
        cash_submit = driver.find_element(By.ID, "cash-button")
        cash_submit.click()
        self.assertEqual(driver.find_element(By.ID, "cash-table-usd").text, 100)

if __name__ == "__main__":
    unittest.main()

CodePudding user response:

cd into your project directory and then

python manage.py runserver

CodePudding user response:

You should use Django's StaticLiveServerTestCase. Below in an example from the LiveServerTestCase section of the documentation of running Selenium tests.

class MySeleniumTests(StaticLiveServerTestCase):
    fixtures = ['user-data.json']

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.selenium = WebDriver()
        cls.selenium.implicitly_wait(10)

    @classmethod
    def tearDownClass(cls):
        cls.selenium.quit()
        super().tearDownClass()

    def test_login(self):
        self.selenium.get('%s%s' % (self.live_server_url, '/login/'))
        username_input = self.selenium.find_element(By.NAME, "username")
        username_input.send_keys('myuser')
        password_input = self.selenium.find_element(By.NAME, "password")
        password_input.send_keys('secret')
        self.selenium.find_element(By.XPATH, '//input[@value="Log in"]').click()
  • Related