【发布时间】:2022-10-14 11:17:51
【问题描述】:
我正在尝试对我的一个观点进行测试,但我不断收到此错误raise ValueError( ValueError: Content-Type header is "text/html", not "application/json"
这是视图功能
def add_to_cart(request):
cart = Cart(request)
if request.POST.get("action") == "post":
product_id = int(request.POST.get("productid"))
product_qty = int(request.POST.get("productqty"))
product = get_object_or_404(Product, id=product_id)
cart.add(product=product, qty=product_qty)
product_qty = cart.__len__()
response = JsonResponse({"qty": product_qty})
return response
这是网址路径
from django.urls import path
from . import views
app_name = "cart"
urlpatterns = [
path("add/", views.add_to_cart, name="add_to_cart"),
]
最后是测试
def test_add_to_cart(self):
response = self.client.post(reverse('cart:add_to_cart'), {
"productid": 3,
"productqty": 1,
"action":'post',
}, xhr=True)
print(response.status_code)
self.assertTrue(response.json(), {'qty':4})
response = self.client.post(reverse('cart:add_to_cart'), {
"productid": 2,
"productqty": 1,
"action":'post',
}, xhr=True)
self.assertTrue(response.json(), {'qty':3})
【问题讨论】:
-
而不是打印
response.status_code您应该断言。检查值是否符合您的预期第一的. -
那是最初用于调试的,我应该删除它,我将测试状态代码并更新问题
标签: python json django unit-testing testing